如何在轨道中创建has_many关系记录?



我有一个具有一些关系的用户模型,我希望用户能够发布帖子。所以我建立了一个后期模型。模型如下所示:

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 认为用户不存在?

user是记录,user_id是整数字段。你混淆了他们。

所以这行不通...

@post = Post.new(user: current_user.id)

而是做...

@post = Post.new(user_id: current_user.id)

或者更好...

@post = Post.new(user: current_user)

您设置user_id: @user的位置也是如此...你可能想要user_id: @user.id

最新更新