【问题标题】:Rails class comparison - If Class.children include AnotherClass.children doRails 类比较 - 如果 Class.children 包含 AnotherClass.children 则
【发布时间】:2015-04-12 04:13:04
【问题描述】:

我希望是个简单的问题。我有几个类 - 用户和食谱 - 两者都有“成分”作为孩子,通过“有很多”的关系。我想运行一个比较来检查 User.ingredients 是否包含每个食谱的成分。

我认为是一个简单的“包含?”查询可以解决这个问题,但在实施时它返回 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 数组上不匹配。这也需要解决吗?

【问题讨论】:

    标签: ruby-on-rails ruby arrays has-many-through comparison-operators


    【解决方案1】:

    你可以像这样比较两个数组:

    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 %>
    

    希望对你有帮助……

    【讨论】:

    • 完美——很有魅力!非常感谢@gabrielhilal。
    • 作为其他访问此内容的任何人的仅供参考 - 答案让我走上了正确的轨道,但引发了误报(即,如果用户和食谱之间只有一个 id 匹配,则显示为真)。我不得不对此进行调整,以便该行计算 '(@user.ingredients.pluck(:id) & recipe.ingredients.pluck(:id)) == recipe.ingredients.pluck(:id)' 我已经把它放到一个辅助方法中来整理一下:'def ingredients_matcher(one, two) (one.ingredients.pluck(:id)) & two.ingredients.pluck(:id)) == two.ingredients.pluck( :id) end' 希望这对某人有用!任何反馈,让我知道。史蒂夫。
    猜你喜欢
    • 2015-06-15
    • 2019-12-08
    • 2021-05-17
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多