我遇到了以下问题:我有很多表,其中一些是嵌套的,另一些则不是。我将我的应用程序分成了一些我认为正确的方法。一个区域应该同时操作一些表格,就像我说的那样:一些模型嵌套其他表格不是。 Rails世界中最好的解决方案是什么? 为了明白这一点,我应该阅读什么?
我尝试使用
accepts_nested_attributes_for
我尝试使用fields_for构建要在相同表单中使用的对象。但它将是一个复杂的形式,因为一些对象包含外键,不幸的是我无法使用超过2个对象获得正确的构建。
我会继续努力。
谢谢!
---- -----编辑
Class Country < ActiveRecord::Base
has_many :states
attr_accessible :nome
# i tried # accepts_nested_attributes_for :state
end
Class State < ActiveRecord::Base
belongs_to :country
has_many :cities
attr_accessible :nome, :country_id
# i tried # accepts_nested_attributes_for :city
# i tried # accepts_nested_attributes_for :country # too
end
这些模型一直持续到我们获得地址模型为止:
Class Adress < ActiveRecord::Base
has_many :bairros_logradouros # we name streets, avenues, parks as logradouros
# here in Brasil, the others models are translated
# to EN here
has_many :logradouros, :trough => :bairros_logradouros # many-to-many
attr_accessible :number, :complement, :other, :another
# i tried # accepts_nested_attributes_for :logradouro
end
设置:国家/地区 - &gt;州 - &gt;城市 - &gt;区(bairro,这里) - &gt; :Logradouro&lt; - &gt; ADRESS。 我尝试在两个方向上构建链,但是我只获得了2个对象,第三个对构建方法带来了一个零问题。
这些表是关于地址的,我应该操纵用户模型tha has_one人,最后有一个地址,我想将地址指向:人员内的:addres_id。
所有这一切都必须在自定义数据控制器上操作,所有CRUD都在这里。
我无法构建整个链:
@addres = @addres.new
@other = @addres.logradouros.build
@another = @other.build_district
@even_more = @another.build_city
....
我学会了使用objects.build和build_object,但我无法构建超过2个嵌套对象。
我是新手。
再次感谢!
答案 0 :(得分:0)
答案 1 :(得分:0)
如果您在Rails 3.1+中使用批量分配白名单(最多但不包括Rails 4),那么如果您使用accepts_nested_attributes_for :logradouros
,则需要attr_accessible :logradouros_attributes
(注意复数logradouros和_attributes in名字)。但是,你可能会遇到更多问题。 Here是一个相关问题。
开始时的一个很好的参考是阅读Rails guide中的所有内容。