2011-04-19 53 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