首先,一个念头 - 大部分时间,产品有很多种类,但每个类别还含有多种产品。也许你的社团应该是多对多的?谈谈你的实际问题。
如果我理解正确,你的问题是关于如何创建数据库中彼此相关的类别和产品,即如何在构建新类别时设置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时,我曾经在这段代码中陷入了一个星期!
非常感谢帮忙:)。 – user659068 2011-04-19 21:55:55
不客气! :) – sscirrus 2011-04-19 22:52:11
伟大的答案!我有两个部分的问题,这完美地回答了第一部分。如果你有一分钟,你会介意在我的问题的第二部分发现[这里]裂缝(http://stackoverflow.com/questions/5813528/how-to-pass-foreign-key-attributes-down-通一个嵌套外形在护栏-3)?它只能用嵌套的形式来处理这个问题。 – FattRyan 2011-04-28 06:39:28