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"}