亲爱的,我有一个Student
模型,我在其中指定了一些name_scope
,例如from_program
,from_year
,from_school
,has_status
,from_course
等......
无论如何,我可以在运行时根据某些标准动态地将不同的named_scope
链接在一起吗?
例如,如果访问数据的用户来自财务部门,我希望能够仅将from_school
和has_status
链接在一起。如果用户是讲师,我希望能够将from_course
,from_school
链接在一起,等等......
我应该使用named_scope
吗?或者我应该回到指定条件的旧方法?
提前感谢您的建议! =)顺便说一句,我正在使用rails 2.3
答案 0 :(得分:5)
我不确定,如果我理解,但我认为你可以这样做:
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
或更一般
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
答案 1 :(得分:2)
您可以尝试这样的事情
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
你可以像这样打电话
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)
以同样的方式传递参数