Я изучаю Rails, строя систему заказов, и я застреваю, пытаясь создать форму для Orders. Где Заказы - это вложенный ресурс для Ресторана. Маршруты:Rails Join Table Nested form_for
resources :restaurants do
resources :orders
resources :recipes
end
Мои модели выглядеть следующим образом:
class Restaurant < ActiveRecord::Base
has_many :orders
has_many :recipes, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes, dependent: :destroy
has_many :recipes, through: :order_recipes
end
class Recipe < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes
has_many :orders, through: :order_recipes
end
Мой контроллер:
@recipes = @restaurant.recipes
@order_recipes = @recipes.map{|r| @order.order_recipes.build(recipe: r)}
И мое мнение:
<%= form_for([@restaurant, @order]) do |order_form| %>
<%= order_form.label :Table_Number %>
<%= order_form.number_field :table_id %>
<%= order_form.fields_for :order_recipes, @order_recipes do |orf| %>
<%= order_form.hidden_field :recipe_ids %>
<%= order_form.label Recipe.where(id: :recipe_id) %>
<%= orf.number_field :quantity %>
Моя текущая проблема отображающая имена eac h рецепт. Кажется, что recipe_id все время передается как null. Моя конечная цель - создать order_recipes, заполняющий столбец количества, и я подумал, что с recipe_id из order_recipes я мог бы также получить доступ к правильному объекту рецепта из БД, чтобы отобразить имя или любые другие соответствующие данные.
Вы забыли о модели OrderRecipes? – Vasseurth
Нет, его там. Кстати, этот ответ работает для меня, по крайней мере, для формы. Все еще борется с передачей параметров. (Http://stackoverflow.com/questions/25235025/rails-4-accessing-join-table-attributes) –