如何在rails中创建has_many关系记录?`

问题描述 投票:1回答:1

我有一个具有某些关系的用户模型,我希望该用户能够发表帖子。所以我建立了一个帖子模型。型号如下图所示:

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"]}。但是User确实存在并且正在传递给表单。然后决定尝试在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认为用户不存在?

ruby-on-rails rails-activerecord
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.