I want to copy the relations of a class A to a class B

class ShoppingList
  has_many :ingredients

class Recipe
  has_many :ingredients

I want to add the ingredients of a recipe to a shopping list, but FROM the recipe page (I won't elaborate why but it makes sense in the UX). Ingredients are the only relation they have in common.

The logic is : On my recipe page, I wish to have a drop-down menu containing my shopping lists. Then, when I select a shopping list and validate, it will add the ingredients of the recipe to the shopping list.

I've been struggling to make this work, I know there's possibly multiple things I did wrong, but here's what I tried :

recipes_controller.rb :

def add_ingredients_to_list
  # call method to find the @recipe
  tmp = ShoppingList.find_by_id(shopping_list_params[:shopping_lists])
  tmp.ingredients << @recipe.ingredients
  redirect_to shopping_list_path(id: tmp.id)


def shopping_list_params
  params.require(:recipe).permit(:shopping_lists, :id)

routes.rb :

resources :recipes do
  post 'add_ingredients_to_list' => "recipes#add_ingredients_to_list"

recipes/show.html.erb :

<%= simple_form_for :recipe, :url => recipe_add_ingredients_to_list_url(@recipe), :method => 'post' do |f| %>
  <%= f.input :id, :input_html => { :value => @recipe.id}, as: :hidden %>
  <%= f.input :shopping_lists, collecton: ShoppingList.all, as: :select %>
  <%= f.button :submit %>
<% end %>

With this code, I'm getting this trace :

Rendered recipes/show.html.erb within layouts/application (122.9ms)
Completed 500 Internal Server Error in 395ms (ActiveRecord: 109.7ms)

ActionView::Template::Error (undefined method `shopping_lists' for #<Recipe:0x000055a4c080af88>):
    54:           <% end %>
    55:           <%= simple_form_for :recipe, :url => recipe_add_ingredients_to_list_url(@recipe), :method => 'post' do |f| %>
    56:             <%= f.input :id, :input_html => { :value => @recipe.id}, as: :hidden %>
    57:             <%= f.input :shopping_lists, collecton: ShoppingList.all, as: :select %>
    58:             <%= f.button :submit %>
    59:           <% end %>
    60:         </div>

app/views/recipes/show.html.erb:57:in `block in _app_views_recipes_show_html_erb___4100323442142788090_47083061551380'
app/views/recipes/show.html.erb:55:in `_app_views_recipes_show_html_erb___4100323442142788090_47083061551380'

My best guess is that the simple_form is not suited for what I want to do, but I really don't know how to make this feature.

Could you help me ?

0 Answers