How to pass an array to fields_for in Rails?

I want to use fields_for for a subset of the records in an association.

I have a Month model that has_many :payments .

But in my form, in my opinion, I want to have only fields_for some of these payments. For instance:

 - fields_for @month.payments.large 

This does not work.

Can I transfer a set of records to fields_for , and not to a regular character ( fields_for :payments )?

+4
source share
2 answers

You can add an additional association for large payments, for example:

 class Month < ActiveRecord::Base has_many :payments has_many :large_payments, :class_name => "Payment", :conditions => "value > 1000000" end 

After that, you can use fields_for usual way:

 - fields_for :large_payments 

I think that encapsulating this logic on the model side is the best approach to presentation.

+5
source

However, you can use an array of objects without creating any additional associations. For example, let's say that in your controller you prepared some array @large_payments, then in the view you can do the following:

 <%= f.fields_for :payments, @large_payments do |payment| %> ... 

Thus, if you have a fairly large form or several form pages, and you do not want to create an additional association for each group that you want to display, you do not need to.

+5
source

All Articles