我想将A类的关系复制到B类中
class ShoppingList
has_many :ingredients
end
class Recipe
has_many :ingredients
end
我想将配方的成分添加到购物清单中,但是从配方页面开始(我不会详细说明原因,但是在UX中有意义)。成分是唯一的共同点。
逻辑是:在我的食谱页面上,我希望有一个包含我的购物清单的下拉菜单。然后,当我选择购物清单并进行验证时,它将把配方的成分添加到购物清单中。
我一直在努力进行这项工作,我知道我可能做错了很多事情,但这就是我尝试过的事情:
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)
end
private
def shopping_list_params
params.require(:recipe).permit(:shopping_lists, :id)
end
routes.rb:
resources :recipes do
post 'add_ingredients_to_list' => "recipes#add_ingredients_to_list"
end
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 %>
使用此代码,我得到了此跟踪:
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'
我最好的猜测是,simple_form不适合我想做的事情,但是我真的不知道如何制作此功能。
你能帮我吗?