将范围写入模型轨道4.0

时间:2015-05-16 05:37:47

标签: ruby-on-rails-4 activerecord

我正在使用rails 4.0开发应用程序。我的博客控制器中有这个代码

@published = params[:published]

@blogs = Blog.published_blogs.where('published >= ? AND published <= ?', (params[:published].to_date).beginning_of_month, (params[:published].to_date).end_of_month)   

published_blogs是我博客模型中的另一个范围。我只想在我的Blog模型中移动此查询。请帮帮我。

我在我的博客模型中试过这个

scope :by_published, lambda{|published| 'published'>=? AND published', (published).to_date.beginning_of_month ,(published).to_date.end_of_month if published.present?}

然后将我的控制器更改为

@blogs = Blog.published_blogs.by_published(params[:published])

1 个答案:

答案 0 :(得分:0)

Rails 4中的范围再次改变 - 这就是我对使用它们感到不安的原因:

scope :by_published, ->(published) { where('published >= ? AND published <= ?', (published).to_date.beginning_of_month ,(published).to_date.end_of_month if published.present?)}

http://edgeguides.rubyonrails.org/active_record_querying.html#passing-in-arguments

class Article < ActiveRecord::Base
  scope :created_before, ->(time) { where("created_at < ?", time) }
end

我个人更喜欢类方法,如果你传递参数,它们实际上是推荐的:

&#34;但是,这只是复制了类方法提供给你的功能。&#34;

class Article < ActiveRecord::Base
  def self.created_before(time)
    where("created_at < ?", time)
  end
end

&#34;使用类方法是接受范围参数的首选方法。仍然可以在关联对象上访问这些方法:&#34;

category.articles.created_before(time)