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

Posted by jstayton on Stack Overflow See other posts from Stack Overflow or by jstayton
Published on 2010-06-05T21:05:25Z Indexed on 2010/06/05 21:12 UTC
Read the original article Hit count: 217

Filed under:
|
|
|

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!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby