是否可以使用可选参数作用域?

ton*_*all 22 activerecord scope ruby-on-rails ruby-on-rails-3

是否可以使用可选参数编​​写一个范围,以便我可以使用和不使用参数调用范围?

就像是:

scope :with_optional_args,  lambda { |arg|
  where("table.name = ?", arg)
}

Model.with_optional_args('foo')
Model.with_optional_args
Run Code Online (Sandbox Code Playgroud)

我可以检查lambda块是否给出arg(如Unixmonkey所描述)但是在调用范围时没有参数我得到了 ArgumentError: wrong number of arguments (0 for 1)

jdo*_*doe 26

Ruby 1.9扩展块具有与方法相同的功能(默认值在其中):

scope :cheap, lambda{|max_price=20.0| where("price < ?", max_price)}
Run Code Online (Sandbox Code Playgroud)

呼叫:

Model.cheap
Model.cheap(15)
Run Code Online (Sandbox Code Playgroud)


z5h*_*z5h 21

是.只需*在方法中使用.

scope :print_args, lambda {|*args|
    puts args
}
Run Code Online (Sandbox Code Playgroud)


kso*_*sol 13

scope :name, ->(arg1, arg2 = value) { ... }几个星期前使用它,如果记忆正确,它运作良好.与ruby 1.9+一起使用


sca*_*er2 9

您可以根据给定的参数有条件地修改范围.

scope :random, ->(num = nil){ num ? order('RANDOM()').limit(num) : order('RANDOM()') }
Run Code Online (Sandbox Code Playgroud)

用法:

Advertisement.random # => returns all records randomized
Advertisement.random(1) # => returns 1 random record
Run Code Online (Sandbox Code Playgroud)

或者,您可以提供默认值.

scope :random, ->(num = 1000){ order('RANDOM()').limit(num) }
Run Code Online (Sandbox Code Playgroud)

用法:

Product.random # => returns 1,000 random products
Product.random(5) # => returns 5 random products
Run Code Online (Sandbox Code Playgroud)

注意:显示的语法RANDOM()特定于Postgres.显示的语法是Rails 4.