How do I create custom “association methods” in Rails 3?

南笙酒味 提交于 2019-12-06 10:36:28

问题


I've read this article, but it's 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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5213407/how-do-i-create-custom-association-methods-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!