Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
nested resources errors array
3 Posts
nested resources errors array

Hello,

I am having a problem with nested resources and displaying validation errors. So take this example: user has_many emails. Now I want to create/update emails from the users/profile page which should go to the emails controller, create a new record and if errors exist, redirect back to the users profile page and display the errors.

What's a good way of doing that ?

Thanks.

Don't try and go to the email controller to create the email. Just create it (using std ActiveRecord API) from the action of your users controller.

The answer to your question depends somewhat on what exactly you're trying to do. If your users/profile page provides multiple bits of email-related functionality that you're handling with AJAX requests, then you'll have to write a bit of JavaScript to display your success or failure messages.

If that's not the case, then I don't understand how you are managing create and update of multiple email addresses from one page. In this case, the possibly overly-simplistic answer is that you should be linking to the emails#new and emails#edit pages for creating and updating emails, respectively. Validation failures on emails#create and emails#update should re-render (not redirect to) the appropriate form. To display errors you include at the top of your view templates.

Controller code generally looks something like:

def new
  @email = Email.new
end

def create
  @user = User.find(params[:user_id])
  @email = @user.emails.new(params[:email])
  if @email.save
    redirect_to user_profile_path(@user)
  else
    render :action => :new
  end
end

I expect you're trying to do something more complicated, though. Can you provide more details?

3 Posts
Login to add your message