开发者

Which type of Rails model association should I use in this situation?

I have two开发者_开发技巧 models/tables in my Rails application: discussions and comments. Each discussion has_many comments, and each comment belongs_to a discussion. My discussions table also includes a first_comment_id column and last_comment_id column for convenience and speed. I want to be able to call discussion.last_comment for the last comment model, but the following (in my discussion model) isn't working to make this happen:

has_one :first_comment, :class_name => "Comment"
has_one :last_comment, :class_name => "Comment"

When I call discussion.last_comment, the following SQL is run:

SELECT * FROM `comments` WHERE (`comments`.discussion_id = 1) LIMIT 1

It's using the discussions.id column to join against comments.discussion_id, when I want it to join discussions.last_comment_id against comments.id.

Am I using the wrong type of association here? Thanks for your help!


Try a belongs_to, rather than a has_one.

The naming might be odd, but the difference between the two is really just about which of the tables holds the foreign key column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜