0

I'm developing a rails application.

I want the user to be able to make a selection between an array of models

In one controller, I create an array of models.

def myController
 @data = []
 @data += [MyData.find(2)]
 @data += [MyData.find(5)]
 @data += [MyData.find(7)]
end

In the view, I can't use the form_for because can't be used in an array, so I have:

<%= form_tag 'myOp' do |f|%>
 <%= fields_for :test, @data do |builder|%>
  <%= render 'sub_form', :f => builder %>
 <% end %>
<% end %>

Now in the sub_form, I want to recieve each of the items of the array, but instead, I'm getting the full array.

How can I get each of the items of the array in the subform?

Is there a better way to do this?

Thanks

2 Answers 2

2

So first in your controller

def my_action
    @datas = MyData.find(2, 5, 7)
end

Then in your view

You need to iterate through the @datas array and yield the fields for each object. That is because fields_for yields fields for one object only, not arrays of objects.

<%= form_tag 'myOp' do |f|%>
    <% @datas.each_with_index do |data, i| %>
        <%= fields_for "test_#{i}", data do |builder|%>
            <%= render 'sub_form', :f => builder %>
        <% end %>
    <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

.@data = [] .@data += [MyData.find(2)] .@data += [MyData.find(5)] .@data += [MyData.find(7)] is an array of objects. Not an array of arrays.
0

I hope this will correct the issue:

<%= form_tag 'myOp' do |f|%>
 <%= fields_for :test, @data.each do |builder|%>
  <%= render 'sub_form', :f => builder %>
 <% end %>
<% end %>

Normally an array object can be seperated using .each method. May that would work here also. Try it.

2 Comments

The code that I posted usually workd on a form_for. The one that you posted is not working. The subform is recieving an Enumerator.
It works as describe here, but it is necessary to allow the owning model of form 'f' to access the data attributes in order to be able to add fields to form 'builder'. Took me quite a while to find that gap in my program. has_many :datas, accepts_nested_attributes_for :datas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.