2011-04-19 76 views
2

我有兩個型號如何傳遞對象ID?

之間的關係

類別型號

class Category < ActiveRecord::Base 
    belongs_to :product 
end 

產品型號

class Product < ActiveRecord::Base 
    has_many :categories 
end 

category_id在產品表,但是當我在我的產品表中創建一個新的產品 category_id一片空白。我是新來的鐵路任何人都可以幫忙嗎?

回答

4

首先,一個念頭 - 大部分時間,產品有很多種類,但每個類別還含有多種產品。也許你的社團應該是多對多的?談談你的實際問題。

如果我理解正確,你的問題是關於如何創建數據庫中彼此相關的類別和產品,即如何在構建新類別時設置product_id的值。

爲了清楚起見,如果您需要,product_id只能設爲類別。畢竟,該類別屬於該產品,因此必須保留其擁有者的ID。

所以,讓我們說,你想建立一個屬於現有產品的新類別 - 你可以這樣做:

# in your view, where you link from products/show.html.erb to category/new.html.erb 
<%= link_to "Build new category for this product", new_category_url(:id => @product.id) %> 
    # you must have @product defined, and you also must have 
    # 'resources :categories' in your routes file 

# in your controller action categories/new, set the new category's product id: 
def new 
    @category = Category.new(:product_id => params[:id]) 
end 

# include a hidden field to contain the product_id in your new form 
<%= form_for @category do |f| %> 
    <%= f.hidden_field :product_id %> 
    ... other fields, labels, etc. 
<% end %> 

# save the record as you normally would (analogous to the code in your comment to @Chowlett). 
@category = Category.new(params[:category]) 
if @category.save 
    redirect_to :action => "list", :notice => "Category saved successfully." 
else 
    render :action => "new" 
end 

上面的代碼可以讓你建立一個產品,然後每個類別一個接-一。因此,我們首先構建您的產品,然後包含從產品/展示頁面到您的類別/新表單的鏈接,並傳入您希望該類別參與的產品的ID。

如果你想在同一時間建立一個產品和一些類別,它有點複雜。欲瞭解更多信息,請看http://railscasts.com/episodes/196-nested-model-form-part-1(這是三部分系列的第一部分)和https://github.com/ryanb/nested_form。除非你對上述基礎知識非常滿意,否則我不建議採取這種行動。當我剛接觸Rails時,我曾經在這段代碼中陷入了一個星期!

+0

非常感謝幫忙:)。 – user659068 2011-04-19 21:55:55

+0

不客氣! :) – sscirrus 2011-04-19 22:52:11

+0

偉大的答案!我有兩個部分的問題,這完美地回答了第一部分。如果你有一分鐘​​,你會介意在我的問題的第二部分發現[這裏]裂縫(http://stackoverflow.com/questions/5813528/how-to-pass-foreign-key-attributes-down-通一個嵌套外形在護欄-3)?它只能用嵌套的形式來處理這個問題。 – FattRyan 2011-04-28 06:39:28

3

首先,您的_id字段位於錯誤的表格中。如果Category belongs_to :product,那麼你的分類表需要一個字段product_id

看它是這樣的:每個產品可以有很多分類 - 還等什麼價值,你希望在一個category_id場找?

如果糾正後仍有問題,請告訴我。

編輯:一旦你建立了表格,你仍然需要告訴Rails鏈接應該是什麼。你有幾個選擇。假設你手上有一個類別,你最好的選擇是new_prod = my_cat.create_product()。或者,您可以使用new_prod = Product.create(:category => my_cat)

之後,你可以在模型一起這樣的聯想:

my_prod.category = my_cat 
my_prod.save 
+0

我在categories表中創建了一個名爲product_id的列,並創建了一個新產品still category_id is null ??我是否需要在新操作中傳遞product_controller中的category_id? DEF新 @product = Product.new 端 DEF創建 @product = Product.new(PARAMS [:產品]) 如果@ product.save redirect_to的:行動=> '列表' 別的 @categories = Category.find(:all) render:action =>'new' end end – user659068 2011-04-19 16:46:05

+0

請幫忙? – user659068 2011-04-19 17:07:30

+0

糾正我,如果我錯了,但如果在產品中使用attr_accessible,Product.create:category => my_cat不會分配類別。 – Alexey 2011-04-19 19:53:55