1

我正在学习 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 我还可以从数据库访问正确的配方对象以显示名称或任何其他相关数据。

4

3 回答 3

0

我假设,你有一家餐厅,它有食谱,它接受订单,订单由 order_recipes 表跟踪。

# controller
@recipes = @restaurant.recipes
@order = @recipes.map{|r| r.order.build}

# view
<%= form_for([@restaurant, @order]) do |order_form| %>
  ...
  <% @order.each do |index, ord| %>
    <%= order_form.fields_for :orders, @order do |orf| %>
      ...
      <%= order_form.label @recipes[index] %>
      <%= orf.number_field :quantity %>

# also in restaurant model
accepts_nested_attributes_for :orders
于 2015-08-02T15:36:36.983 回答
0

最终我得到了这个问题中发布的答案:Rails 4 Accessing Join Table Attributes 我现在只是在努力传递正确的参数,但形式是正确的。

于 2015-08-02T16:30:22.887 回答
0

在您的控制器中尝试:

@order_recipes = @recipes.map{|r| @order.build_order_recipes(recipe: r)}
于 2015-08-02T15:47:25.200 回答