无法访问parent_to关系的父级

时间:2016-03-01 19:08:49

标签: ruby-on-rails ruby activerecord associations

具有以下关联:

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

在创建Comment的实例后,在rails控制台中,我可以访问它关联的Post

comment = current_user.comments.create(post_id: 2, body: "Sint voluptatem dolor a veniam pariatur")
comment.post # returns it's parent

但是控制器中的相同操作返回nil

@comment = current_user.comments.create(comment_params)
@comment.post # => nil
@comment.post_id # => 2

comment_params的内容是:

puts comment_params
=> {"body"=>"Sint voluptatem dolor a veniam pariatur", "post_id"=>"2"}

1 个答案:

答案 0 :(得分:1)

确保数据库中存在post id 2。

post看起来不存在,这就是它返回nil的原因。

相关问题