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!