繁体   English   中英

如何在Ruby on Rails中将类方法链接在一起?

[英]How to chain class methods together in Ruby on Rails?

我在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

有没有更优雅的方法来编写第一种方法?

最好将opendraft方法链接在一起,如下所示:

def self.payable
  open.not(:draft)
end

不幸的是,这不起作用。

也许您可以使用范围?

scope :payable, -> { open.where.not(:delivery_status => "draft") }

你可以这样使用

YouModel.payable

要链接否定查询,可以使用以下技巧:

def self.payable
  open.where.not(id: draft)
end

如果您不关心是否返回ActiveRecord::Relation对象,则另一种选择是使用- ,它返回Array

def self.payable
  open - draft
end

我个人将使用scope而不是类方法进行查询: https : //guides.rubyonrails.org/active_record_querying.html#scopes 所以:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM