Rails 4范围与参数

时间:2014-05-01 17:11:47

标签: 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) }

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

2 个答案:

答案 0 :(得分:28)

非常简单,只是没有参数的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

答案 1 :(得分:3)

来自Rails edge docs

  

" 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)} }