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
2
  • This could help stackoverflow.com/questions/13367426/… Commented Apr 14, 2014 at 8: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? Commented Apr 14, 2014 at 8:58

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Concerning option 2, I believe you should have: format.js { render :template => "classrooms/create_differently.js.erb" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.