Dynamic named_scope depending on specific criteria

Darling, I have a model Studentin which I indicated in it name_scope, for example. from_program, from_year, from_school, has_status, from_course, Etc.

Anyway, can I dynamically bind different named_scopedynamically depending on certain criteria at runtime?

for example, if the user accessing the data is "Finance", I want to be able to link only from_schooland has_status. if the user is a teacher, I want to be able to chain from_course, from_schooltogether and so on ...

Should i use named_scope? or should I just go back to the good old way of defining conditions?

Thanks for your suggestions in advance! =) btw I am using rails 2.3

+3
source share
2 answers

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
+5
source

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 it that

  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)

+2

All Articles