【发布时间】:2020-05-29 13:50:19
【问题描述】:
我有一个包含一些关系的用户模型,我希望用户能够发布帖子。所以我建立了一个帖子模型。型号如下图:
User.rb
belongs_to :plan
has_one :profile
has_many :posts
has_many :follower_relationships, class_name: "Follow", foreign_key: "following_id"
has_many :followers, through: :follower_relationships, source: :follower
has_many :following_relationships, class_name: "Follow", foreign_key: "user_id"
has_many :following, through: :following_relationships, source: :following
Post.rb
belongs_to :User
所以我尝试创建一个记录:
def new
@post = Post.new(user: current_user.id)
end
def create
@post = @user.posts.create(post_params.merge(user_id: @user))
if @post.save
flash[:success] = "Post successfully created"
redirect_to @post
else
flash[:danger] = @post.errors.messages.inspect
render 'new'
end
end
但是,它返回错误{:User=>["must exist"]}。但是用户确实存在并且正在被传递到表单中。然后决定尝试在 rails 控制台中创建一个帖子。
o = User.first.posts.build(image_url: "https://images.pexels.com/photos/188777/pexels-photo-188777.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", title: "some", subtitle: "thing", body: "body")
o.save!
它返回了ActiveRecord::RecordInvalid (Validation failed: User must exist)
为什么rails认为用户不存在??
【问题讨论】:
-
你可以在这里找到类似问题的答案stackoverflow.com/questions/62019390/…
标签: ruby-on-rails rails-activerecord