问题描述:

With the following 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

In rails console after creating an instance of Comment, I can access it's associated Post:

comment = current_user.comments.create(post_id: 2, body: "Sint voluptatem dolor a veniam pariatur")

comment.post # returns it's parent

But the same action in the controller, returns nil:

@comment = current_user.comments.create(comment_params)

@comment.post # => nil

@comment.post_id # => 2

The content of comment_params is:

puts comment_params

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

网友答案:

Make sure the post with id 2 is present in the database.

Looks like the post doesn't exist, which is why it is returning nil.

相关阅读:
Top