1

My schema is as follows:

   create_table "ingredients", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "recipe_ingredients", force: :cascade do |t|
    t.integer "recipe_id"
    t.integer "ingredient_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "recipes", force: :cascade do |t|
    t.string "name"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

On my index page, I would like to list all the recipes and then either have link or button that sorts the recipes by the amount of ingredients each recipe has. I've been toying with this for a couple hours now and getting closer but being a newb, my brain isn't quite making the leap. Right now I have some code in the RecipesController in #index that takes in some params from the view file:

  <%= button_to "sort by ingredient amount", {:controller => "index", :action => "update", :order => true}, :method=>:post  %>

the code in the controller so far is something like this:

  def index
    if params[:order] = true
      Recipe.all.each do |r|
        r.ingredients.each do |i|
          ???
        end
      end
    else
      @recipes = Recipe.all 
    end
  end

I'm not sure how to use .order when accessing an association such as the recipes_ingredients. This could also be the totally bassackwards way to do it.

Demian Sims
  • 871
  • 1
  • 14
  • 29
  • What is `ingredient amount` ? – Vishal Dec 10 '18 at 05:07
  • The amount of ingredients each recipe has. It's just one value for now - the ingredient object itself. – Demian Sims Dec 10 '18 at 05:25
  • https://stackoverflow.com/questions/16996618/rails-order-by-results-count-of-has-many-association – Surya Dec 10 '18 at 05:51
  • Possible duplicate of [Rails order by results count of has\_many association](https://stackoverflow.com/questions/16996618/rails-order-by-results-count-of-has-many-association) – Surya Dec 10 '18 at 05:53

1 Answers1

0

Yes you can find the data based on ingredients like these

def index
  if params[:order] = true
    Recipe.left_joins(:ingredients).group(:id).order('COUNT(ingredients.id) DESC')
  else
    @recipes = Recipe.all 
  end
end