[英]How to chain class methods together in Ruby on Rails?
I've got this in my Rails 5 model: 我在Rails 5模型中有了这个:
def self.payable
open.where.not(:delivery_status => "draft")
end
def self.draft
where(:delivery_status => "draft")
end
def self.open
where(:payment_status => "open")
end
Is there a more elegant way to write the first method? 有没有更优雅的方法来编写第一种方法?
It would be great to chain the open
and draft
methods together like this: 最好将
open
和draft
方法链接在一起,如下所示:
def self.payable
open.not(:draft)
end
Unfortunately, this doesn't work. 不幸的是,这不起作用。
Maybe you can use scopes? 也许您可以使用范围?
scope :payable, -> { open.where.not(:delivery_status => "draft") }
You can use this like that 你可以这样使用
YouModel.payable
To chain negated queries you can use this trick: 要链接否定查询,可以使用以下技巧:
def self.payable
open.where.not(id: draft)
end
Another alternative if you don't care if an ActiveRecord::Relation
object is returned is using -
, which returns an Array
: 如果您不关心是否返回
ActiveRecord::Relation
对象,则另一种选择是使用-
,它返回Array
:
def self.payable
open - draft
end
I would personally use scope
s instead of class methods for queries: https://guides.rubyonrails.org/active_record_querying.html#scopes . 我个人将使用
scope
而不是类方法进行查询: https : //guides.rubyonrails.org/active_record_querying.html#scopes 。 So: 所以:
scope :draft, -> { where(:delivery_status => "draft") }
scope :open, -> { where(:payment_status => "open") }
scope :payable, -> { open.where.not(id: draft) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.