Search code examples
ruby-on-railsrubyarrayshas-many-throughcomparison-operators

Rails class comparison - If Class.children include AnotherClass.children do


Simple question I hope. I've a couple of classes - User and Recipe - both of which have 'ingredients' as children via has-many-through relationships. I'd like to run a comparison that checks to see if User.ingredients include the ingredients for each Recipe.

I thought a simple 'include?' query would work this out, but it's returning nil when implemented. Got a feeling this is because I'm applying it to a class rather than array (although doesn't User.ingredients return an array?!), though not sure how I should adjust this to get it working - I've tried converting items to arrays, plucking ids out, etc. but nothing has working yet.

Any help much appreciated! Steve.

Here's the controller code:

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

And the (abridged) view that's returning nil even when both contain the same ingredients:

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

One other point - testing this in the console, I've noticed running .include? on arrays of ingredient ids don't match if they're in the wrong order. Does this also need addressing?


Solution

  • You can compare two array like so:

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

    In this way, you can do something like:

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

    I hope it helps...