Rails: rendering partial in div on click

I am creating a webapp that has an interface divided into two parts, a menu bar and a content area. The menu bar contains a list of the names of all blogs that the user has written. When the heading is clicked, the content area must change to display the posts of this blog.

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

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

And in my content area, I have:

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

2.) Therefore, in my opinion, this should call the show method for the blog controller. There, the method has the following:

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

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

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

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

4.) So my show blog has this code:

 <% =@blog.title %> <% =@blog.user _id %> 

EDIT: Actually, I searched and found that I could not use the "rendering" method from the resource folder - where did I put js.erb then? I moved it to the blog view folder, the home view folder (index.html.erb) and just the / view / folder. The error has disappeared, but the link does not work ...

EDIT: Put show_blog.js.erb in my views / blogs folder as it calls its blog controller. Nothing happens when I click the link and there are no JS errors displayed on the console. Is js called at all?

EDIT: Modified to reflect my final answer.

+4
source share
2 answers

A very simple solution at the end. Partially called blog.title, blog.user_id, but @blog was the actual parameter that was passed. It was just necessary to switch to @ blog.title and @ blog.user_id.

0
source
 @blog = Blog.find(params[:id]) respond_to do |format| format.js { render :show_blog } end 

This is not the default logic of Rails.

You did not specify the name of the method, suppose

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

Rails will then search for show_blog.js.erb in views/blogs and display this file.

In addition, you need to pass the actual instance to partial, because patrial is a standalone piece of code and does not know what @blog is:

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

Source: https://habr.com/ru/post/1487363/


All Articles