0

I am trying to load new data onto a page after a user has chosen which data to load out of a list. Before the user has chosen, I want the first item on the list to show its data.

So, in my html.erb file:

<div id="detailsPA">
     <%=  render @app.snaps, :toolkit_view => false %>
   <div id="test">
     <%= render :partial =>'snaps/snap_details', :locals=> {:snap => @app.snaps[0]} %>
   </div>
</div>

@app.snaps is an array of items with a bunch of data. Here, an item in this array is called a snap.

The first render @app.snaps renders the array into links. The second, renders the data of an item in the list.

Here is the code for the list of links.

<%=link_to snap.name,{controller: 'snaps', action: 'snap_details', id: snap.id, remote: true}, {method: :get, class: 'snapButton'}%>

In order for the second render to work I have to tell it which item (or in this case snap) was chosen.

When a link is clicked on its data should replace the old data. My controller looks like:

def snap_details
  @snap = Snap.find(params["id"])
  render :json=>{:key=> @snap.id}
end

Then my js file looks like:

$(document).ready(function(){
   $('.snapButton').on('ajax:success', function(event, data, status, xhr){
      $('#test').empty();
      $('#test').html("<%=escape_javascript render(:partial =>'snaps/snap_details', :locals=> {:snap => @snap})%>");
  });

});

But when I click on a link the new data doesn't replace the old data.

I am new to Ruby on Rails and Javascript. I feel like I am close to what I want but I am missing something very important.

4

1 回答 1

1

您正在呈现这样的 json 对象:({ key: '123' }只有 id)。您无权访问您的实例变量@snap

尝试以下操作:

def snap_details
  @snap = Snap.find(params["id"])
end

snap_details.js.erb在 snaps 文件夹中创建一个新文件。由于您remote: true在链接中使用,请求将在您的控制器中作为 JavaScript 处理。

snap_details.js.erb

$('#test').empty();
$('#test').html("<%=escape_javascript render('snaps/snap_details', {snap: @snap})%>");

希望这可以帮助!

于 2013-07-18T21:22:03.607 回答