如何创建自定义的"关联方法"在Rails 3中? [英] How do I create custom "association methods" in Rails 3?

查看:121
本文介绍了如何创建自定义的"关联方法"在Rails 3中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过本文但它是Rails的1.x的。

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)

在Rails 3中,什么是该做的正确方法是什么?

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

推荐答案

做事的Rails 3的方法通常是不使用find方法,而是范围,直到你开始遍历集合这将延迟实际的数据库调用。

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:

类回复...

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

,然后使用它:

 spammy_messages = user.replies.spaminess(:very)

或使用它在一个视图

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

这篇关于如何创建自定义的"关联方法"在Rails 3中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆