开发者

ActiveRecord Associations About :autosave and self

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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜