开发者

How do I create custom "association methods" in Rails 3?

I've read this article, but it's 开发者_StackOverflow社区for Rails 1.x.

I'd really like to create my own association methods:

user = User.find(1)

# Example of a normal association method
user.replies.create(:body => 'very informative. plz check out my site.')

# My association method
user.replies.find_by_spamminess(:likelihood => :very)

In Rails 3, what's the proper way of doing this?


The Rails 3 way of doing things is often to not use find methods, but rather scopes, which delays the actual database call until you start iterating over the collection.

Guessing at your first example, I would do:

in class Reply ...

  scope :spaminess, lambda {|s| where(:likelyhood => s) }

and then using it:

 spammy_messages = user.replies.spaminess(:very)

or to use it in a view

spammy_messages.each do |reply|
   ....
end


I think I found it!

If you search for "association extensions" the Rails API page for ActiveRecord::Assications, you'll see that this is the syntax (copied from that link):

class Account < ActiveRecord::Base
  has_many :people do
    def find_or_create_by_name(name)
      first_name, last_name = name.split(" ", 2)
      find_or_create_by_first_name_and_last_name(first_name, last_name)
    end
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜