我有 3 个模型:类别、帐户和子帐户
关系是:
帐户 has_many :sub_accounts
类别 has_many :sub_accounts
我想获取给定帐户未使用的所有类别的列表。 我在类别模型中的方法目前看起来像:
class Category < ActiveRecord::Base
def self.not_used_by(account)
Category.find_by_sql("select * from categories where id not in(select category_id from sub_accounts where account_id = #{account.id})")
end
end
我的问题是,是否有比使用 SQL 更简洁的替代方法?
注意。我目前正在使用 Rails 3(测试版)
最佳答案
您可以将方法移至帐户模型并通过执行以下操作来使用更多 ActiveRecord:
class Account < ActiveRecord::Base
def unused_categories
Category.where("id NOT IN (?)", sub_accounts.map(&:category_id))
end
end
然后你可以这样做:
Account.first.unused_categories
关于ruby-on-rails - 是否有等同于使用嵌套子查询的 ActiveRecord,即 ... where NOT IN(select...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2616978/