当我不知道要添加多少个时,如何从 rails 3 form_for 创建关联模型的多个实例? [英] How can I create multiple instances of an assosiated model from a rails 3 form_for when I don't know how many I'm going to add?
问题描述
我有一个 form_for 来创建一个新的估计",并且这些估计中的每一个都可以有无限数量的项目"(这就像一个零件号,但它会有自己的一组属性).在提交创建新估算的表单之前,我希望能够创建尽可能多的关联项目模型的实例,然后让它创建与该估算相关的所有关联项目.
I have a form_for that creates a new 'Estimate' and each of these estimates can have an unlimited number of 'Items' (this is like a part number, but it will have it's own set of attributes). I would like to be able to create as many instances of the associated Items model as I want to before I submit the form that creates the new Estimate, and then have it create all of the associated Items that go with that Estimate.
我在 form_for 和 accepts_nested_attributes_for 上的 API 中阅读了很多内容,我在谷歌上进行了广泛的搜索,并观看了有关嵌套模型表单的 railscasts,并且我已经阅读了我的 rails 3 书,但我已经尚未找到一种轨道方式"以从相同的形式一次性创建所有这些新对象.在 Railscast 中,Ryan 在控制器中有这样的东西:
I've read a lot in the API on form_for and accepts_nested_attributes_for, I've googled extensively, and I've watched the railscasts about nested model forms, and I've read through my rails 3 book, but I've yet to find a 'rails way' to create all of these new objects in one go from the same form. In the railscast, Ryan has something like this in the controller:
def new
@estimate = Estimate.new
3.times { @estimate.items.build }
end
但是,我不知道每个估算将包含多少项.我也不确定我应该在视图中使用哪个 fields_for 语法,但我知道我可能必须使用 JavaScript 来动态创建新的表单字段.
However, I do not know how many items are going to be on each estimate. I'm also not sure which fields_for syntax I should be using in the view, but I do understand I'll probably have to use JavaScript to dynamically create new form fields.
以下是我的模型的关联方式:
Here is how my models are related:
class Estimate < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items
end
和:
class Item < ActiveRecord::Base
belongs_to :estimates
end
那么,有什么想法吗?就像我说的,我可以让我的应用执行此操作(我可能会使用大量 AJAX),但我希望有人可能有更漂亮的解决方案.
So, any ideas? Like I said, I can make my app do this (I'll probably use a lot of AJAX), but I was hoping someone might have a prettier solution.
谢谢.
推荐答案
???你的方式是最好的 Rails 方式.也许您不知道为项目构建表单?通过 Rails 指南或 Rails API,您可以编写以下内容:
??? your way is the best Rails Way. Perhaps you don't know to build a form for items? By Rails Guides or Rails API's, you can write following:
<%= form_for @estimate do |f| %>
<p>
<%= f.label :xxx %>
<%= f.text_field :xxx %>
</p>
<%= f.fields_for :items do |item_field| %>
<p>
<%= item_field.label :yyy %>
<%= item_field.text_field :yyy %>
</p>
<% end %>
<% end %>
而且你可以使用非常好的 Gem,'nested_form'.请参阅:https://github.com/ryanb/nested_form
And you can use the sooooo good Gem, 'nested_form'. see: https://github.com/ryanb/nested_form
这篇关于当我不知道要添加多少个时,如何从 rails 3 form_for 创建关联模型的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!