我正在学习 Rails 构建一个订购系统,但我一直在尝试为 Orders 构建一个表单。其中 Orders 是 Restaurant 的嵌套资源。路线:
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 %>
我目前的问题是显示每个食谱的名称。似乎 :recipe_id 一直作为 null 传递。我的最终目标是能够构建 order_recipes 填充数量列,并且我认为拥有 order_recipes 中的 recipe_id 我还可以从数据库访问正确的配方对象以显示名称或任何其他相关数据。