1

簡單的問題,我希望。我有幾個班 - 用戶和食譜 - 這兩個班都通過有許多關係的「成分」作爲孩子。我想運行一個比較來檢查User.ingredients是否包含每個食譜的配料。Rails類的比較 - 如果Class.children包含AnotherClass.children做

我以爲一個簡單的'包括?'查詢可以解決這個問題,但是它在實現時返回nil。有一種感覺,這是因爲我將它應用到類而不是數組(儘管不會User.ingredients返回數組?),但不知道如何調整它以使其工作 - 我試過轉換項目數組,撥出ID等,但沒有任何工作。

任何幫助非常感謝!史蒂夫。

這裏的控制器代碼:

def meals 
    @recipes = Recipe.all 
    @user = current_user #from my user authentication 
end 

而且(有刪節)查看遭到返回nil,即使都含有相同的成分:

<% @recipes.each do |recipe| %> 
     <% if @user.ingredients.include?(recipe.ingredients) %> 
      <!-- ... --> 
       <td> 
        <%= recipe.name %> 
       </td> 
     <% end %> 
    <% end %> 

另一點 - 在控制檯測試此,我注意到運行.include?如果它們的順序不正確,那麼在成分ID數組上不匹配。這是否也需要解決?

回答

2

你可以比較兩個數組,像這樣:

a = [1,2,3] 
b = [1,2] 
c = [4,5] 

a & b 
#=> [1, 2] 
a & c 
#=> [] 
(a & c).empty? 
#=> true 

通過這種方式,你可以這樣做:

<% @recipes.each do |recipe| %> 
    <% unless (@user.ingredients.pluck(:id) & recipe.ingredients.pluck(:id)).empty? %> 
     <!-- ... --> 
      <td> 
       <%= recipe.name %> 
      </td> 
    <% end %> 
<% end %> 

我希望它可以幫助...

+0

完美 - 工作原理魅力!感謝一羣@gabrielhilal。 – SRack 2015-02-11 19:22:32

+1

作爲參與此次訪問的其他人的參考 - 答案讓我走上了正確的軌道,但拋出了誤報(即如果用戶和配方之間只有一個ID匹配,則表明它是真實的)。我不得不調整這個,所以行計算'(@ user.ingredients.pluck(:id)&recipe.ingredients.pluck(:id))== recipe.ingredients.pluck(:id)',我已經把這個放到輔助方法中來整理一下:'def ingredient_matcher(one,two) (one.ingredients.pluck(:id))&two.ingredients.pluck(:id))== two.ingredients.pluck (:id) end'希望對某人有用!任何反饋,讓我知道。史蒂夫。 – SRack 2015-02-12 12:04:03