Reputation: 12759
Let's say I have two classes: Post
and Comment
class Post < ActiveRecord::Base
belongs_to :newest_comment, :class_name => "Comment", :foreign_key => "newest_comment_id", :dependent => :destroy
has_many :comments, :dependent => :destroy, :autosave => false
def set_comment(new_comment)
comments << new_comment # <= still auto saves
self.newest_comment = new_comment # why do I need the self?
save
end
end
class Comment < ActiveRecord::Base
The :newest_comment attribute is a slight optimization that is giving me a hard time. I need the actions inside set_comment
to happen inside a transaction.
Did I read the documentation wrong or should the new_comment
not be autosaving. I'm also wondering why the self
is needed.
You can see my two comments in the code.
Upvotes: 0
Views: 241
Reputation: 16515
Instead of using belongs_to, you should use #has_one, which is the same thing as #has_many, but with an automatic limit of 1, thus:
class Post < ActiveRecord::Base
has_many :comments, :order => "created_at DESC"
has_one :newest_comment, :class_name => "Comment", :order => "created_at DESC"
end
This way, you won't even need to muck with autosave and such, since the newest comment will always be the right one. If the newest comment isn't the one with the latest #created_at, simply change the order by clause.
Upvotes: 2