user1491961
user1491961

Reputation:

Rails: Rendering partial in div on click

I'm building a webapp that features a UI split into two sides, a menu bar and a content area. The menu bar has a listing of the titles of all blogs that a user has written. When a title is clicked, the content area should change to show the posts of that blog.

1.) So on my menu bar, I have:

<%= link_to blog.title, blog, :remote=>true %>

And in my content area, I have:

<div id="contenthere"></div>

2.) So by my understanding, this should trigger the show method of the blog controller. There, I have the following in the method:

@blog = Blog.find(params[:id])

respond_to do |format|
   format.js { render :show_blog }
end

3.) Which should go look for a file called show_blog.js.erb in views/blogs folder:

$("#contenthere").html("<%=escape_javascript(render :partial=>"show_blog")%>");

Which will take my div with commenthere id and render the _show_blog.html.erb partial (located in the blog view folder) with the blog parameter equal to the @blog parameter that was set in my blog controller.

4.) So my show blog partial has this code:

<%[email protected] %>
<%[email protected]_id %> 

EDIT: Actually, I search around and found out that I can't use the method 'render' from within the assets folder-- where do I put the js.erb then? I've moved it to the blog view folder, home view folder (index.html.erb), and just the /view/ folder... The error is gone, but the link is not working...

EDIT: Put the show_blog.js.erb in my views/blogs folder, since it's the blog controller calling it. Nothing happening when I click the link and no JS errors shown in console. Is the js being called at all?

EDIT: Changed to reflect my final answer.

Upvotes: 5

Views: 7515

Answers (2)

Joe Half Face
Joe Half Face

Reputation: 2333

@blog = Blog.find(params[:id])

respond_to do |format|
   format.js { render :show_blog }
end

That is not Rails default logic.

You didn't provided, how method is called, suppose

   def show_blog
    @blog = Blog.find(params[:id])
    respond_to do |format|
       format.js 
    end
    end

Then, Rails will look for show_blog.js.erb in views/blogs and render that file.

Also, you need to pass actual instance to partial, because patrial is stand-alone chunk of code and doesn't know, what @blog is:

$("#contenthere").append("<%=j render :partial=>"show_blog", :locals=>{:@blog=>@blog}%>");

Upvotes: 1

user1491961
user1491961

Reputation:

Very simple solution in the end--- The partial was calling for blog.title, blog.user_id, but @blog was the actual param that was passed. Just had to change to @blog.title and @blog.user_id.

Upvotes: 0

Related Questions