Rails加入表嵌套的form_for

时间:2015-08-02 14:35:52

标签: ruby-on-rails join activerecord nested-form-for

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在您的控制器中尝试:

@order_recipes = @recipes.map{|r| @order.build_order_recipes(recipe: r)}

答案 2 :(得分:0)

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