form_for non-AR model - fields_for Array attribute doesn't iterate

我与影子孤独终老i 提交于 2019-11-30 07:27:11

I think the correct technique is:

= form_for @parent, :url => new_parent_path do |f|
  - @parent.bars.each do |bar|
    = f.fields_for "bars[]", bar do |r|
      = r.object.inspect

Quite why it can't be made to Just Work I'm not sure, but this seems to do the trick.

I think that it can be done without the need of each:

= form_for @parent, :url => new_parent_path do |f|
  = f.fields_for :bars do |r|
    = r.object.inspect

You need to set some methods that are expected in the parent class to identify the collection.

class Parent
  def bars_attributes= attributes
  end
end

And you also will need to make sure that the objects in the array respond to persisted (so you cannot use strings) :(

I ditched the fields_for and added multiple: true

= form_for @parent, :url => new_parent_path do |f|
  - @parent.bars.each_with_index do |bar, i|
    = f.text_field :bars, value: bar, multiple: true, id: "bar#{i}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!