ruby on rails -向作用域添加参数



我有一个ActiveRecord查询,例如:

@result = stuff.limit(10)

where stuff是一个带有where子句、order by等的活动记录查询

现在我想为什么要传递这样的神奇数字给控制器?那么,您认为为"limit(10)"定义一个范围并使用它是一个好的做法吗?语法是怎样的呢?

确实有多种方法可以做到这一点,类方法是@Dave Newton指出的一种。如果你想使用作用域,方法如下:

scope :max_records, lambda { |record_limit|
  limit(record_limit)
}

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

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

如果你想了解作用域和类方法之间更深层次的区别,请查看这篇博客文章。

希望有帮助。干杯!

井口示波器是用于这个

作用域允许您指定常用的Arel查询,这些查询可以作为关联对象或模型上的方法调用来引用。使用这些作用域,您可以使用前面介绍的所有方法,例如where、join和include。所有作用域方法都将返回一个ActiveRecord::Relation对象,该对象允许在其上调用其他方法(例如其他作用域)。

来源:http://guides.rubyonrails.org/active_record_querying.html范围

如果你觉得你有一些常见的查询,或者你需要在你的查询中有一些常见的链接。那么我建议你使用作用域来防止重复。

现在回答在你的例子

中作用域是什么样子
class YourModel < ActiveRecord::Base
  scope :my_limit, ->(num) { limit(num)} 
  scope :your_where_condition, ->(num) { where("age > 10").mylimit(num) } 
end

在Rails范围内传递参数

作用域定义

scope :name_of_scope, ->(parameter_name) {condition whatever you want to put in scope}

调用方法

name_of_scope(parameter_name)

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

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

如果你总是(或"几乎"总是)想要这个限制,使用默认作用域:

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

跳过默认作用域:

> Stuff.unscoped.all.size
=> 8

Rails模型的作用域,参数:

scope :scope_name, -> (parameter, ...) { where(is_deleted: parameter, ...) }  

或:

scope :scope_name, lambda{|parameter, ...| where(is_deleted:parameter, ...)} 

最新更新