说我有这个范围:
scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
Run Code Online (Sandbox Code Playgroud)
我想要一个等效的范围
scope :has_zipcode, lambda { |zip| where(zipcode: zip) }
Run Code Online (Sandbox Code Playgroud)
有没有办法将一个范围别名?比如像
alias :with_zipcode, :has_zipcode
Run Code Online (Sandbox Code Playgroud)
PS我知道这是一个人为的,不切实际的例子,只是想知道它是否可能!
谢谢!
activerecord alias ruby-on-rails named-scopes rails-activerecord
我一直在尝试使用范围来链接Arel查询,而不仅仅是使用我在控制器中编写的一些冗长的逻辑。但是作用域比仅获取所有记录然后用某种逻辑筛选它们要慢。那么,我想知道为什么范围会更好。
这是我在做什么:
首先,作用域方式
issue.rb:
scope :answered, joins(:answers).order('answers.created_at desc')
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")
Run Code Online (Sandbox Code Playgroud)
在questions_controller.rb中:
@dogs_recently_answered = Question.answered.dogs.uniq[0..9]
@cats_recently_answered = Question.answered.cats.uniq[0..9]
@mermaids_recently_answered = Question.answered.mermaids.uniq[0..9]
Run Code Online (Sandbox Code Playgroud)
然后在视图中,循环浏览这些实例变量(现在是最多包含10个元素的数组)并显示结果。
以下是加载页面所需的时间(五个不同的时间):
在535毫秒内完成200 OK(查看:189.6毫秒| ActiveRecord:46.2毫秒)
在573毫秒内完成200 OK(查看:186.0毫秒| ActiveRecord:46.3毫秒)
在577毫秒内完成200 OK(查看:189.0毫秒| ActiveRecord:45.6毫秒)
在532毫秒内完成200 OK(查看:182.9毫秒| ActiveRecord:46.1毫秒)
在577毫秒内完成200 OK(查看:186.7毫秒| ActiveRecord:46.9毫秒)
现在,凌乱的控制器方式...
@answers = Answer.order("created_at desc")
@all_answered = []
@answers.each {|answer| @all_answered << answer.question}
@recently_answered = @all_answered.uniq
@dogs_all_answered = []
@cats_all_answered = []
@mermaids_all_answered = []
@recently_answered.each …Run Code Online (Sandbox Code Playgroud) 在我的Rails 3.2.8应用程序中,我有一些命名范围,我想在某些情况下链接在一起.
所以,例如,我有这两个范围:
scope :by_status, lambda { |status| if status == "All" then WorkRequest.all else WorkRequest.find_all_by_status(status) end }
scope :in_date_range, lambda { |start_date, end_date| includes([:person, :pier_module]).where("(status_date >= ?) AND (status_date <= ?)", start_date, end_date) }
Run Code Online (Sandbox Code Playgroud)
我单独使用它们,但我也希望能够像这样一起调用它们:
WorkRequest.by_status("Accepted").in_date_range("2012-01-01", "2012-10-02")
Run Code Online (Sandbox Code Playgroud)
当我尝试它时,它抱怨in_date_range不是Array的方法.
但我有另一个范围,
scope :active, includes([:person, :pier_module]).where("status = 'New Request'")
Run Code Online (Sandbox Code Playgroud)
如果我这样做
WorkRequest.active.in_date_range("2012-01-01", "2012-10-02")
Run Code Online (Sandbox Code Playgroud)
有用!显然,活动范围返回一个Relation,而lambda范围返回Arrays,因此无法链接.
我想知道为什么简单的范围和lambda范围之间的区别,参数如何影响它,以及我是否可以做任何事情,而不是编写组合范围,我已经完成了.
scope :by_status_in_date_range, lambda { |status, start_date, end_date| includes([:person, :pier_module]).where("(status = ?) AND (status_date >= ?) AND (status_date <= ?)", status, start_date, end_date) }
Run Code Online (Sandbox Code Playgroud)
工作,但不是很干(因为我也需要个别范围)或Rails-ish.在这里和其他地方搜索我已经看到类似的问题,但似乎没有适用于这种情况,我试图用参数链接两个lambda.