2013-05-30 64 views
-1

我有CategoriesProducts。一個產品有關係 belongs_to :categoryrails創建頁面從

在類別顯示頁面我有一個按鈕來添加一個新產品。此按鈕進入創建新產品的頁面,但我需要將該類別分配給新產品。

如何將id從我所在的category頁面傳遞到新產品?因此,如果我處於類別Electronic中,單擊「添加產品」,此產品將自動關聯到Eletronic類別。

希望你能明白我想要什麼。 謝謝

+1

您需要顯示一些嘗試自己找到答案然後尋求幫助而不是要求別人爲你找到答案。 – Justin

+0

問題是我已經試圖找到如何做到這一點,但我沒有找到我真正想要的東西。 –

回答

0

首先,我將決定每個產品是否包含在類別,還是它與簡單的關聯一個類別。提示它包含將是:

  • 您希望每個產品都有一個「父」類別。
  • 您預計每個產品將始終顯示在其父類別的上下文中。

當且僅當你相信這是事實,我會被誘惑範疇內的產品資源。

# routes.rb 
resources :categories do 
    resources :products 
end 

# products_controller.rb (SIMPLIFIED!) 
class ProductController < ApplicationController 
    before_filter :get_category 

    def new 
    @product = @category.products.build 
    end 

    def create 
    @product = @category.products.build(params[:product]) 

    if @product.save 
     redirect_to @product 
    else 
     render template: "new" 
    end 
    end 

    def get_category 
    @category = Category.find(params[:category_id]) 
    end 
end 

如果您這樣做,rails會確保您的產品與正確的類別相關聯。奇蹟發生在@category.products.build,它根據關係自動設置category_id。

如果你寧願保留類別和產品的簡單聯想,我只用一個查詢參數按照埃裏克·安德烈斯的答案,但我會忍不住來處理它的方式略有不同:

# link: 
new_product_path(category_id: @category.id) # So far, so similar. 

# products_controller.rb 
class ProductsController < ApplicationController 
    def new 
    @product = Product.new 
    @product.category_id = params[:category_id].to_i if params[:category_id] 
    end 
end 

# new.erb 
<%= f.hidden_field :category_id %> 

這幾乎只是一種風格上的差異。埃裏克的答案也會起作用 - 我只是喜歡在模型本身設置值,而不是讓視圖擔心參數等。

+0

感謝您的好解釋。我不會使用嵌套元素,因爲我是一名新手,但我還知道軌道可以做什麼。 –

1

您需要通過鏈接中的category_idnew_product_path(category_id: @category.id)

你還需要在你的產品形式的現場保存類別的ID,如<%= f.hidden_field :category_id, params[:category_id] %>

+0

謝謝,這真的有幫助。我不知道hidden_​​field,我不得不改變link_to。我正在使用button_to。 –