2013-02-08 77 views
0

我有了像这样的关系的产品型号:在rails中,我可以创建一个具有多个关系的产品吗?

has_many :product_images
has_many :product_specs

的关系都工作正常,我感到高兴。

当我创建我的新产品时,我将控制器设置为在产品创建后保存product_image和product_spec。问题是:我需要多个规格和产品图像。有没有办法在新产品的表单中添加多个product_images和多个product_specs,并在产品创建时一次性创建它们?另外,用户将决定他们需要添加多少图片和规格。

我很欣赏任何人的建议。

回答

1

你应该阅读rubyonrails API更深一点;)link

class Member < ActiveRecord::Base 
    has_many :posts 
    accepts_nested_attributes_for :posts 
end 

现在,您可以设置或通过属性哈希相关的岗位模型更新属性。

对于没有id键的每个散列,除非散列还包含一个计算结果为true的_destroy键,否则将新实例化一条新记录。

params = { :member => { 
    :name => 'joe', :posts_attributes => [ 
    { :title => 'Kari, the awesome Ruby documentation browser!' }, 
    { :title => 'The egalitarian assumption of the modern citizen' }, 
    { :title => '', :_destroy => '1' } # this will be ignored 
    ] 
}} 

member = Member.create(params['member']) 
member.posts.length # => 2 
member.posts.first.title # => 'Kari, the awesome Ruby  documentation browser!' 
member.posts.second.title # => 'The egalitarian assumption of the modern citizen' 
+0

我尝试,我只是不知道在哪里看。 :)很好知道属性散列,这是有道理的。谢谢! – jmcharnes 2013-02-08 19:09:37

+0

是的。表单的实施取决于你。可能会选择宝石或您的个人实施。 – FUT 2013-02-08 19:12:08

1

我会建议看Ryan Bates的nested form宝石。这正是你正在寻找的。

这里是link。 它的Railscasts是here

+0

我来看看它,谢谢! – jmcharnes 2013-02-08 18:59:36

相关问题