将参数添加到范围

Boh*_*ohn 23 ruby-on-rails ruby-on-rails-3.2 rails-activerecord

我有一个ActiveRecord查询,例如:

@result = stuff.limit(10)
Run Code Online (Sandbox Code Playgroud)

stuff是一个活动的记录查询,其中where子句,order by等等...

现在我想为什么要将这样的魔法数字传递给控制器​​?那么你认为定义"limit(10)"的范围并使用它是一个好习惯吗?语法怎么样?

And*_*des 47

确实存在多种这样的方法,类方法是@Dave Newton指出的方法.如果您想使用范围,请按以下步骤操作:

scope :max_records, lambda { |record_limit|
  limit(record_limit)
}
Run Code Online (Sandbox Code Playgroud)

或者使用Ruby 1.9"stabby"lambda语法和多个参数:

scope :max_records, ->(record_limit, foo_name) {   # No space between "->" and "("
  where(:foo => foo_name).limit(record_limit)
}
Run Code Online (Sandbox Code Playgroud)

如果您想了解范围和类方法之间的更深层差异,请查看此博客文章.

希望能帮助到你.干杯!

  • 在上面的stabby lambda示例中的小问题:在stab运算符和打开参数列表的括号之间不允许有空格. (2认同)

Ank*_*itG 20

Well Scopes就是为了这个

作用域允许您指定常用的Arel查询,这些查询可以作为对关联对象或模型的方法调用进行引用.使用这些范围,您可以使用之前涵盖的每种方法,例如where,joins和includes.所有范围方法都将返回一个ActiveRecord :: Relation对象,该对象将允许在其上调用更多方法(例如其他范围).

资料来源:http://guides.rubyonrails.org/active_record_querying.html#scopes

因此,如果您认为您有一些常见的查询,或者您需要在查询中进行某种链接,这对许多人来说是很常见的.然后我建议你去寻找范围以防止重复.

现在回答一下范围在您的情况下的样子

class YourModel < ActiveRecord::Base
  scope :my_limit, ->(num) { limit(num)} 
  scope :your_where_condition, ->(num) { where("age > 10").mylimit(num) } 
end
Run Code Online (Sandbox Code Playgroud)


小智 16

在Rails范围中传递参数

范围的定义

scope :name_of_scope, ->(parameter_name) {condition whatever you want to put in scope}
Run Code Online (Sandbox Code Playgroud)

呼叫方法

name_of_scope(parameter_name)
Run Code Online (Sandbox Code Playgroud)


Dav*_*ton 2

范围看起来就像任何其他(尽管您可能更喜欢类方法),例如,

class Stuff < ActiveRecord::Base
  def self.lim
    limit(3)
  end
end

> Stuff.lim.all
=> [#<Stuff id: 1, name: "foo", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 2, name: "bnar", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 3, name: "baz", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">]
> Stuff.all.length
=> 8
Run Code Online (Sandbox Code Playgroud)

如果您总是(或“几乎”总是)想要该限制,请使用默认范围:

class Stuff < ActiveRecord::Base
  attr_accessible :name, :hdfs_file

  default_scope limit(3)
end

> Stuff.all
=> [#<Stuff id: 1, name: "foo", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 2, name: "bnar", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">,
 #<Stuff id: 3, name: "baz", created_at: "2013-03-01 17:58:32", updated_at: "2013-03-01 17:58:32">]
> Stuff.all.length
=> 3
Run Code Online (Sandbox Code Playgroud)

要跳过默认范围:

> Stuff.unscoped.all.size
=> 8
Run Code Online (Sandbox Code Playgroud)