Rails 4范围与参数

升级Rails 3.2。 到Rails 4.我有以下范围:

# Rails 3.2 scope :by_post_status, lambda { |post_status| where("post_status = ?", post_status) } scope :published, by_post_status("public") scope :draft, by_post_status("draft") # Rails 4.1.0 scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) } 

但我无法找到如何做第2和第3行。 如何从第一个范围创建另一个范围?

很简单,只是没有参数的lambda:

 scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) } scope :published, -> { by_post_status("public") } scope :draft, -> { by_post_status("draft") } 

或更短的:

 %i[published draft].each do |type| scope type, -> { by_post_status(type.to_s) } end 

来自Rails边缘文档

“Rails 4.0要求范围使用可调用对象,例如Proc或lambda:”

 scope :active, where(active: true) # becomes scope :active, -> { where active: true } 

考虑到这一点,您可以轻松地重写代码:

 scope :by_post_status, lambda { |post_status| where('post_status = ?', post_status) } scope :published, lambda { by_post_status("public") } scope :draft, lambda { by_post_status("draft") } 

如果您希望支持许多不同的状态并发现这很麻烦,以下内容可能适合您:

 post_statuses = %I[public draft private published ...] scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) } post_statuses.each {|s| scope s, -> {by_post_status(s.to_s)} }