2011-03-10 71 views
3

親愛的所有,我有一個Student模型,我已經指定了一些name_scope,例如, from_programfrom_yearfrom_schoolhas_statusfrom_course等...動態`named_scope`取決於某些標準

有反正,我可以鏈中不同named_scope一起動態地取決於某些指標分析運行期間?

例如,如果訪問數據的用戶來自Finance,我希望能夠將from_schoolhas_status鏈接在一起。如果用戶是講師,我想能夠鏈接from_course,from_school在一起,等等......

我應該使用named_scope?還是應該回到規定條件的古老方式?

感謝您提前提出的建議! =)BTW我使用軌道2.3

回答

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 
+0

耶你明白我需要實現,但你一般情況下是沒有得到結果,因爲當你做一個'send','named_scope'立即運行,因此它不會將所有named_scopes鏈接在一起=(我試圖避免第一種方法,因爲它們可以很好地規定,因爲它們被允許指定他們希望的學生羣根據範圍檢索alr允許... =(但感謝您的建議,儘管非常接近! – Staelen 2011-03-10 09:00:37

+0

不客氣! ;]關於一般方法:我已經測試了它,對於組合的命名範圍(通過名稱或發送添加),它仍然可以,只產生一個查詢...我有一個應用程序,我用這種方法,如果我做在控制檯中_Order.send(:edited).send(:by_code,3)_我得到_Order加載(0.3ms)SELECT * FROM'orders' WHERE((code LIKE'%3%')AND('orders'.'狀態'='編輯'))_ – santuxus 2011-03-10 10:35:45

+0

我試過用這種方式運行,但它沒有返回任何結果,它只是返回學生類本身... – Staelen 2011-03-11 01:34:59

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) 

以同樣的方式,你可以傳遞參數

+0

這是不是我居然問...但感謝您的建議 – Staelen 2011-03-10 06:32:15