【问题标题】:named_scope or find_by_sql?named_scope 还是 find_by_sql?
【发布时间】:2010-05-02 04:56:23
【问题描述】:
我有三个模型:
这些关联是:
- 用户获奖无数
- 奖杯有很多奖项
- 奖励属于用户
- 奖品属于奖杯
- 用户通过奖励获得了许多奖杯
因此user_id是award中的fk,trophy_id是award中的fk。
在 STI 模型的 Trophy 模型中,有一个 trophy_type 列。我想返回一个获得特定奖杯的用户列表——(trophy_type = 'GoldTrophy')。用户可以多次获得同一个奖杯。 (我不想要不同的结果。)
我可以使用 named_scope 吗?把它们串起来怎么样?还是我需要使用 find_by_sql?无论哪种方式,我将如何编码?
【问题讨论】:
标签:
sql
ruby-on-rails
associations
named-scope
【解决方案1】:
如果你想沿着 named_scope 路线走,你可以这样做:
将 has_many :users 添加到 Trophy,例如:
has_many :users, :through => :awards
还有下面的named_scope:
named_scope :gold, :conditions => { :trophy_type => 'GoldTrophy' }
您可以调用以下代码:
Trophy.gold.first.users
您需要调用“.first”,因为 named_scope 将返回一个集合。不理想。也就是说,在您的情况下,既不使用 find_by_sql 也不使用 named_scope 可能是完全合适的。使用good old怎么样:
Trophy.find_by_trophy_type('GoldTrophy').users
这将完全满足您的需求,而无需深入研究 SQL。
【解决方案2】:
我总是对“find_by_sql”感到满意 你可以使用它
使用 find_by_sql 如下
User.find_by_sql("select u.id, u.name, t.trophy_type
from users u, awards a, trophies t
where a.user_id=u.id and
t.trophy_id=a.id and
t.trophy_type = 'GoldTrophy'"
)
我不确定使用“named_scope”但试试这个
class User < ActiveRecord::Base
named_scope :gold_trophy_holder,
:select=>" users.id, users.name, trophies.trophy_type",
:joins => :awards, "LEFT JOIN awards ON awards.id = trophies.award_id"
:conditions => ['trophies.trophy_type = ?', 'GoldTrophy']
end