This is taking me ages. I'm sure I have an incorrect understanding of partials but I've done plenty of reading and don't seem to be getting anywhere.
These are the steps I am trying to create.
a) A user clicks on a graph rendered in javascript (d3.js
library) (on http://blabla/graph/data
b) Ajax is triggered and returns the name of the thing that is clicked (in graph.js
)
var node = svg.selectAll(".node")
.on("click", function(d) { getprofile(d); });
function getprofile(d){
$.ajax({url: "/graph/show",
type: "GET",
dataType: 'json',
data: {name: d.name},
success:function(result) {
console.log(result);
$('.profile-content').html(result);}});}
c) The name is passed to the show action of the graph_controller.rb
to perform a database lookup
def show
@user = User.find_by name: params[:name]
render :partial=>'profile', :user => @user
end
The database lookup works fine and the console tells me that user is returned. Great.
d) Now I want to show the result of the database lookup in the same page that the user clicked in the first page, in a partial views/graph/_profile.html.erb
. This is where I get confused about how the @user variable gets passed to the partial.
What I have in the partial is:
<div>Profile details</div>
<div class='profile-content'></div>
<div>User</div>
<%= @user.name %>
but I get the error NoMethodError in Graph#data
with a highlight of the line
<%= @user.name %> `undefined method `name' for nil:NilClass`
in the partial. This is triggered before the page loads it seems
However, if the partial contains <%= @user %>
instead of <%= @user.name %>
then I can see no errors in the console and it returns an object with all the correct fields for the user. The partial is rendered on the page, but there is nothing where the <%= @user %> should be
Basically how do I get the partial to update and show me the object? Constructive would be nice instead of 'read a textbook'. If you don't like the question please just don't answer.
答案 0 :(得分:0)
在服务器端,您不需要渲染局部视图,而是渲染视图:
def show
@user = User.find_by name: params[:name]
render 'profile'
end
从views / graph / _profile.html.erb重命名您的部分 to:&#39; views / graph / profile.html.erb&#39;
如果您坚持在views / users / show.html.erb
中使用partial<%= render 'profile', user: @user %>
这将搜索文件app / views / _profile.html.erb