20

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
allegutta
  • 5,626
  • 10
  • 38
  • 56
  • This could help http://stackoverflow.com/questions/13367426/rendering-a-partial-from-a-controller-in-rails?rq=1 – Pavan Apr 14 '14 at 08:22
  • 1
    The problem I have is that the .js.erb file I am trying to render is in another view folder (the create method is in the post_controller and I am trying to render a .js.erb in the pages view from the post_controller). Any suggestions? – allegutta Apr 14 '14 at 08:58

1 Answers1

34

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
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • 7
    Concerning option 2, I believe you should have: `format.js { render :template => "classrooms/create_differently.js.erb" }` – Henry May 12 '15 at 03:01