2013-04-05 20 views
0

下面的查詢在某些情況下返回nil軌轉換的包括查詢,返回零到範圍拉姆達

scope :claim_one, where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL ").includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL') 

我想查詢轉換成一個lambda函數,它由返回的零的護理查詢如下;

scope :claim, (lambda do |claim| where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL ").includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL', claim) unless claim.nil? end) 

,因爲我不認爲它有正確的軌道語法

謝謝

+0

你好下面的代碼。對不起,「照顧零」是什麼意思?你想避免ActiveRecord :: RecordNotFound錯誤,或者當查詢返回沒有結果時返回一個不同的值? – jpgeek 2013-04-05 15:59:00

+0

還有一件事:是'聲明'你想傳遞給查詢的參數,還是你想將它綁定到你的查詢結果? – jpgeek 2013-04-05 16:10:07

回答

0

不知道如果我完全理解(見上述評論)後不工作,但我希望這將有所幫助。我認爲你的代碼的結果將是一個ActiveRecord :: Relation,它沒有記錄,而不是零。我假設「索賠」是您想要傳入的參數。如果是這種情況,您可以按如下方式添加它。

處理lambda範圍的首選方法現在好多了;只使用一個類的方法:

def self.claim_one(claim) 
    return [whatever you want] unless claim 
    where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL "). 
    includes(:instructor_assignments). 
    where('instructor_assignments.user_id IS NULL') 
end 

我建議以下,雖然讓你的範圍更容易分開使用,更容易理解和測試,只是織補俊俏:

def self.incomlete() 
    where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL ") 
end 

def self.without_instructor() 
    includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL') 
end 

要調用該方法,我會用類似的東西:

result = YourModel.incomplete.without_instructor 
if result.empty? 
    # do yo funky "ain't got no records dance" 
else 
    # record jackpot! 
end 

這是否回答你的問題?

+0

您可能還需要在'self self.claim_one(claim)'中使用'references(:instructor_assignments)'遵循範圍定義' - 另請參見http://blog.remarkablelabs.com/2012/12/what-s-新的活躍記錄護欄-4-倒計時至2013 – novemberkilo 2013-04-09 07:44:58

0

很好,我應該在一個更好的方法

我使用從Ryan Bates CanCan gem

在我看來,康康舞寶石說的事情,我有以下代碼:

<% if can? :claim, @workshop %> 
    <%= link_to claim_workshop_path(@workshop), :method => :post , :class => "mybtn btn-mini claim-workshop-button" do %> 
    <%= t(:Claim) %> 
    <%= content_tag(:i, "", :class => "icon-thumbs-up").html_safe %> 
<% end %> 
<% end %> 

我希望能夠使用從Ryan Bates CanCan te:索賠能力爲此,我需要一個範圍能夠使用該查詢,如上面的鏈接中所述。但有時查詢不會返回結果 - 或無 - 。

在我ability.rb文件我有一個使用範圍

f user.role == "admin" || user.role = "scheduler" 
    can :manage, :all 
    can :claim , Workshop.claim do |workshop_instance| 
     # workshop_instance.can_claim? 
     workshop_instance.instructor_assignments.nil? 
    end 
    else 
    can :read, :all 
    end 

在類用戶,我定義的範圍需要它來獲取我的結果

scope :claim, where(" location_id IS NOT NULL OR start_time IS NOT NULL ").includes(:instructor_assignments).where('instructor_assignments.user_id IS NOT NULL')