views:

63

answers:

1

If I have a single page with many forms of existing records:

index.html.haml

- for selection in @selections
  - form_for selection, :method => :put do |form|
    = form.collection_select :user_id, @current_account.users, :id, :full_name

and then this for submits to and update action:

selections_controller.rb

def update
  selection = Selection.find(params[:id])
  if selection.update_attributes(params[:selection])
    flash[:notice] = "Save!"
    redirect_to selections_path
  else
    flash[:errors] = "Errors"
    render :index
  end
end

How do I handle error messages if I have these multiple forms on the same page. i.e if I want to use:

selection.errors.on(:user_id)

for one of the forms?

A: 

Usually you would want to use the error_msg_for helper.

= error_messages_for object

However in you case because you're rendering multiple forms based on the update of a signle one you have a bit more work to do.

First your update action should repopulate @selections and make the selection that failed to update available to the view as an instance variable.

def update
  @selection = Selection.find(params[:id])
  if @selection.update_attributes(params[:selection])
    flash[:notice] = "Save!"
    redirect_to selections_path
  else
    @selections = Selection.find ....
    flash[:errors] = "Errors"
    render :index
  end
end

Next filter this information into your forms.

index.html.erb

- for selection in @selections
  - form_for selection, :method => :put do |form|
    = error_messages_for form.object if form.object.id = @selection.id
    = form.collection_select :user_id, @current_account.users, :id, :full_name
EmFi
I am getting this error: @#<Selection:0x0000010276a000>' is not allowed as an instance variable name
Cameron
What line does the error correspond to.
EmFi
I think i fixed it by using error_messages_for @selection
Cameron