开发者

Subclassing ActiveRecord accessors

What is the recommended way to wrap an ActiveRecord accessor?

Given something like

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

I would like to be able to make it that, for example, @post.comments returns randomly sorted comments.

Of course I could create another method, like random_comments, but I would like to know if开发者_如何学JAVA there's a less error prone way (I don't want to have to remember to call the random_comments method).

Calling super doesn't work, as the comments method is created reflectively on the Post class and not inherited.

So how would you do it?


You may define default order like

has_many :comments, :order => "RAND()" 

RAND() will works only if database engine supports so, (Mysql supports)


Hope this helps..

class Post < ActiveRecord::Base
  has_many :comments

  def comments_with_randomness
    comments_without_randomness.shuffle
  end

  alias_method_chain :comments, :randomness
end

Now, calling @post.comments should return comments in random order. But, remember, it would be an array and not an active relation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜