Rails 3: How to create a named scope based on Controller's method?

谁都会走 提交于 2019-12-04 17:00:43

Use a lambda to make a dynamic scope, and keep the session info out of the model:

In your model:

class Post < ActiveRecord::Base
  scope :relevant, lambda {|demo_mode|
     joins(:publisher).
     where("publishers.user_type #{demo_mode ? '' : 'NOT'} LIKE 'demo'")
  }
end

And then in the controller:

posts = Post.relevant(demo_mode?)

Try something like this

class Post < ActiveRecord::Base

    scope :relevant, joins("INNER JOIN users ON (users.user_type = 'demo')").where("publisher_id = users.id")

end

If I understand correctly, the demo state is determined by the session so only the controller knows about it. On the other hand, the controller (or possibly the view) is the only place where you would want to query the scope. If all of this is correct, I would add a method to ApplicationController like this:

class ApplicationController < ActionController::Base
  def relevant_posts
    Post.joins(:publisher).
      where("publishers.user_type #{demo_mode? ? '' : 'NOT'} LIKE 'demo'")
  end

  ...
  helper_method :relevant_posts # if you want it to be available in views
end

Technically, this is not a named scope. Rails 3, however does not make much of a difference between named scopes and the standard query interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!