How do I pass an array to fields_for in Rails?

∥☆過路亽.° 提交于 2019-12-01 05:12:07

问题


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

I have a Month model, which has_many :payments.

But in my form in my view I only want to have fields_for some of those payments. For example:

- fields_for @month.payments.large

This doesn't work.

Can I pass a set of records to fields_for, rather than the usual symbol (fields_for :payments) approach?


回答1:


You can add 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 in common way:

- fields_for :large_payments

I think to encapsulate this logic on a model side is a better approach then in the view.




回答2:


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

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

That way if you've got a pretty big form or multiple pages of forms, and you don't want to have to create an additional association for each group that you want to display, you don't have to.



来源:https://stackoverflow.com/questions/3623973/how-do-i-pass-an-array-to-fields-for-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!