簡體   English   中英

Rails聯接表嵌套form_for

[英]Rails Join Table Nested form_for

我正在學習Rails構建訂購系統,而我一直試圖為訂購構建表單。 其中,訂單是餐廳的嵌套資源。 路線:

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,我也可以從數據庫訪問正確的配方對象以顯示名稱或任何其他相關數據。

我假設,您有一家餐廳,有食譜,有訂單,訂單由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

在您的控制器中嘗試:

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

最終,我得到了這個問題的答案,可以正常工作: Rails 4訪問聯接表屬性現在,我只是在努力傳遞正確的參數,但是表格是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM