Dynamic `named_scope` depending on certain criterias
dear all, i have a Student
model that i've specified some name_scope
in it, e.g. from_program
, from_year
, from_school
, has_status
, from_course
, etc...
i开发者_如何学JAVAs there anyway that i can chain the different named_scope
together dynamically depending on certain criterias during runtime?
for example, if the user accessing the data is from Finance, i want to be able to chain from_school
and has_status
together only. if the user is the lecturer, i want to be able to chain from_course
, from_school
together, and so on...
should i use named_scope
? or should i just fall back to the good old way of specifying conditions?
thanks for your suggestions in advance! =) btw i'm using rails 2.3
I'm not sure, if I understood, but I think you could do something like this:
class Student
named_scope from_program, lambda{|program| :conditions => {:program => program}}
named_scope from_year, lambda{|year| :conditions => {:year => year}}
named_scope has_status, lambda{|status| :conditions => {:status => status}}
def self.from_finance(school, status)
self.from_school(school).has_status(status)
end
end
or more general
def self.get_students(params)
scope = self
[:program, :year, :school, :course].each do |s|
scope = scope.send("from_#{s}", params[s]) if params[s].present?
end
scope = scope.has_status(params[:status]) if params[:status].present?
scope
end
You can try something like this
Class User extend ActiveRecord::Base belongs_to :semester named_scope :year, lambda { |*year| if year.empty? || year.first.nil? { :joins => :semester, :conditions => ["year = #{CURRENT_SEMESTER}"]} else { :joins => :semester, :conditions => ["year = #{year}"]} end } end
You can call like this
User.year # defaults to CURRENT_SEMESTER constant User.year() # same as above User.year(nil) # same as above; useful if passing a param value that may or may not exist, ie, param[:year] User.year(2010)
In the same way you can pass parameters
精彩评论