I am trying to build a form for my users where they can enter up to 3 addresses for themselves. After an address is created, it can be marked as inactive and won’t count toward the 3. I am using accepts_nested_attributes_for :addresses in my User model and I’ve tried a few things in my form, but I can’t get fields_for to show existing addresses and new addresses when the existing addresses are scoped.
These are a few things I’ve tried:
In the controller:
(3 - @user.addresses.active.count).times { @user.addresses.build }
This gives me all of the existing, active addresses but no new ones:
<%= f.fields_for :addresses, @user.addresses.active do |address| %>
<%= address.text_field :line_1 %>
<% end %>
This gives me existing and new addresses, but it includes the inactive ones:
<%= f.fields_for :addresses do |address| %>
<%= address.text_field :line_1 %>
<% end %>
Is there a way to combine these to get new AND scoped records?
From what I have found it isn’t possible to explicitly change the scope and show fields for new records by changing the parameters passed to
fields_for.But what ended up solving my problem is the fact that when passing a symbol to
fields_for(for example:fields_for :addresses) the default scope of the model is going to be used. So I setdefault_scope where(:status => 'active')on my address model and nowfields_forwill only show the fields for active addresses and the fields for new addresses.I also needed to sort these addresses by the date they were created. This was possible by changing the default sort on the
has_many :addressesrelation in the user model. So while it doesn’t seem there is a way to explicitly state what scopes to use in the parameters forfields_for, there are ways around it. If anyone can explain how to do this I will gladly mark that answer as correct.