In my application, a Language has many Phrases. Here is my code:
#language model
has_many :phrases
accepts_nested_attributes_for :phrases
#phrase model
validates_presence_of :value
belongs_to :language
#languages controller
def edit
@language = Language.find(params[:id])
# Let's say we only want to update some of the phrases (e.g. by
category, date, etc)
@phrases = @language.phrases.all(:limit => 3)
end
def update
@language = Language.find(params[:id])
if @language.update_attributes(params[:language])
flash[:notice] = "Successfully updated language."
redirect_to edit_language_path(@language)
else
render :action => 'edit'
end
end
# project edit view
<% form_for @language do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :phrases, @phrases do |phrases_form| %>
<p>
<%= phrases_form.label :value %>
<%= phrases_form.text_field :value %>
</p>
<% end %>
<p><%= f.submit %></p>
<% end %>
When I submit the form, if at least one of the phrases being saved is
an existing record, every single phrase corresponding to @language
will be validated, instead of running validations only in the three
phrases being updated. That problem isn't present when all of the
phrases being saved are new records.
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby