Rails 4范围与参数

Vic*_*tor 12 ruby-on-rails ruby-on-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) }
Run Code Online (Sandbox Code Playgroud)

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

Зел*_*ный 33

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

scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) }
scope :published, -> { by_post_status("public") }
scope :draft, -> { by_post_status("draft") }
Run Code Online (Sandbox Code Playgroud)

或更短的:

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


wva*_*aal 6

来自Rails 边缘文档

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

scope :active, where(active: true)

# becomes 
scope :active, -> { where active: true }
Run Code Online (Sandbox Code Playgroud)


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

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") }
Run Code Online (Sandbox Code Playgroud)

如果您有许多不同的状态想要支持并且觉得这很麻烦,那么以下可能适合您:

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)} }
Run Code Online (Sandbox Code Playgroud)