Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering an action in another controller

(Rails 2.3.5)

I have two scaffolds: Directories & Users

For a Directory show action (say Show action: "\directories\2"), I took the User\New form and made it a partial so the user can add users to the Directory. What I can't figure out is how in the create action I can return to "\directories\2\show" if there are any validation errors. Returning if the User.save is successful works fine, I just can't figure out how to format a Render action to return to the directory and display error messages and fields in the New User partial.

This works fine if a save is successful, using the same thing if there is an error will work except error_messages will not be displayed (I know that error messages are only suppose to be passed on a Render, not a redirect, but I can not figure out the syntax involved for a render action when an id parameter is involved):

format.html { redirect_to directory_path(@user.directory_id) }

Users Create Action called by partial in Direcory Show action: def create @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        flash[:notice] = 'User ' + @user.name+ ' was  successfully created.'
        format.html { redirect_to directory_path(@user.directory_id) }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        # what to do here to successfully return to 'directories\show\(@user.directory_id)'
        # and what to do here that successfully passed the error_messages
      end
    end
  end

Thanks for any help - hopefully that makes sense

like image 205
Reno Avatar asked Jan 03 '11 00:01

Reno


1 Answers

To render an action from another controller you need to specify the template you want to render.

render :template => 'other_controller/view_template_name'

P.S: Keep in mind that you'll have to define any instance variables that the other controller action defines which are necessary for the view to render because rendering a template will not call the other controller's function before rendering the view.

like image 143
Pan Thomakos Avatar answered Nov 09 '22 00:11

Pan Thomakos