Car*_*ela 2 ruby-on-rails rails-activerecord
我有一个模特
Email
Run Code Online (Sandbox Code Playgroud)
和一个实例方法
def sent_to_user?(user)
self.who_to == user
end
Run Code Online (Sandbox Code Playgroud)
who_to是另一个实例方法,用于检查一些复杂的东西.
在后台有更多的东西在那里,所以我不能轻易地把它变成一个activerecord查询.
我想做的事情如下:
scope :sent_to_user, -> (user) { sent_to_user?(user)}
@user.emails.sent_to_user
Run Code Online (Sandbox Code Playgroud)
并返回仅为'sent_to_user?'返回true的电子邮件?
试过
scope :sent_to_user, -> (user) { if sent_to_user?(user)}
Run Code Online (Sandbox Code Playgroud)
....等等.
不太确定如何构建该范围/类方法
你不能(至少不应该)以这种方式使用范围.范围用于返回ActiveRecord关系,其中可以链接其他范围.如果要使用作用域,则应生成必要的SQL以在数据库中执行过滤.
如果要在Ruby中过滤结果并返回数组,则应使用类级方法,而不是范围:
class Email < ActiveRecord::Base
def self.sent_to_user(user)
select { |record| record.sent_to_user?(user) }
end
end
Run Code Online (Sandbox Code Playgroud)