Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Render a .js.erb from another controller?

How can I render a .js.erb from a controller that doesn't belong to the view it is going to be rendered in?

For example: How can I render create.js.erb in my pages view, from a post_controller?

post_controller.rb

def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @post }
        format.js #{I think I need something in here?}
      else
        format.html { render action: 'new' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end
like image 228
allegutta Avatar asked Apr 14 '14 08:04

allegutta


1 Answers

It seems there are several ways to achieve this:

respond_to do |format|
    format.js { :location => path_to_controller_method_url(argument) }
end

How do you respond_to another js file in the controller using Ruby on Rails?

respond_to do |format|
    format.js {
       :template => "classrooms/create_differently.js.erb", 
       :layout => false
    }
end

Render alternate view in ruby on rails

respond_to do |format|
    format.js { render :file => "/path/to/save.js.erb" }
end
like image 158
Richard Peck Avatar answered Oct 04 '22 05:10

Richard Peck