Reputation: 941
I have the following relationships
class user
has_many cars
has_many journeys, :through => :cars
accepts_nested_attributes_for :journeys
end
class car
belongs_to user
belongs_to journey
end
class journey
has_many car
has_many users, :through => :cars
end
I have a form to edit of both an existing user and/or journey:
<%= simple_form_for @user, :url => edit_user_path(@user), :method => :put do |f| %>
<%= f.input_field :email %>
<%= f.simple_fields_for :journey, @journey do |j| %>
<%= f.input_field :name %>
<% end %>
<% end %>
I have a validation on the @user.email attribute. If this fails it returns the form correctly with all the @user attributes present. However, it clears any value I might have put in the @journey.name attribute input field.
This isn't very user friendly as the user obviously has already filled this field in. How do I stop this from happening?
EDIT: Updated with an answer based on the information below
In the end I passed settled on the following. The :journeys
provided me with the requisite rails functionality to repopulate the form correctly on a validation error and the if statement ensured it only ever displayed the required instance:
<%= simple_form_for @user, :url => edit_user_path(@user), :method => :put do |f| %>
<%= f.input_field :email %>
<%= f.simple_fields_for :journeys do |j| %>
<% if @journey.id == j.object.id %>
<%= f.input_field :name %>
<% end %>
<% end %>
<% end %>
Upvotes: 0
Views: 249
Reputation: 25049
Don't specify the @journey
on your simple_fields_for - that's not the instance you're validating and repopulating. Let Rails handle it - it will pick @user.journeys
for you.
Upvotes: 2