如何在 rails 中创建 has_many 关系记录?`
How to create a has_many relation record in rails?`
我有一个具有某种关系的用户模型,我希望用户能够发帖。所以我设置了一个 post 模型。型号如下:
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
然而,它returns错误{:User=>["must exist"]}
。但是用户确实存在并且正在传递给 form.Then 决定尝试在 rails 控制台中创建一个 post。
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
我有一个具有某种关系的用户模型,我希望用户能够发帖。所以我设置了一个 post 模型。型号如下:
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
然而,它returns错误{:User=>["must exist"]}
。但是用户确实存在并且正在传递给 form.Then 决定尝试在 rails 控制台中创建一个 post。
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