2016-03-01 51 views
0

用下面的关联:不能访问父的belongs_to的关系

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一个实例后,我可以访问它的相关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

确保postid 2存在于数据库中。

看起来像post不存在,这就是为什么它返回nil