我有以下模型:
class AuthorizedDriver < ActiveRecord::Base
belongs_to :car
def authorized?
!self.authorized_until.nil? && self.authorized_until.to_date >= Time.current.to_date
end
end
我希望能够做到:
def show_authorized_drivers
@car = Car.find(params[:id])
@authorized_drivers = @car.authorized_drivers.where(authorized?: true)
end
我知道我可以在特定字段中执行此操作,但是我想使用上面的authorized?
功能(或稍后使用其他功能)。
对此任何指导将不胜感激,谢谢!
我正在使用Rails 4.1.4和Ruby 2.1.2。
将以下内容添加scope
到您的Driver
模型中:
scope :authorized, -> { where('authorized_until >= ?', Time.current) }
然后,您可以向授权驾驶员查询汽车,如下所示:
@authorized_drivers = @car.authorized_drivers.authorized
更新(回答您的评论):如果需要添加其他条件,则有两个选择。
您可以将两个条件合并为一个范围:
scope :authorized, -> {
where('authorized_until >= ?', Time.current).where(status: 'Active')
}
或者,您可以添加另一个范围:
scope :active, -> { where(status: 'Active') }
并链接范围:
@authorized_drivers = @car.authorized_drivers.authorized.active
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句