weixin_33709590 2014-01-25 19:34 采纳率: 0%
浏览 27

使用ajax渲染部分

In my rails app I have a model Song. On one of the user's profile pages user_music_path(@user) I'm rendering all of their songs.

People can also like these songs, which is set up and working, I just want to use AJAX instead of page refreshes. The problem I'm having is when using ajax, I get the error undefined local variable or method "song" when I'm clicking the link "like".

Here is some of my code:

User's Music Page views/users/music.html.erb

...
<ul class="playlist list-group">
  <%= render @songs %>
</ul>

views/songs/_song.html.erb

<li class="list-group-item">
  <p class="pull-right">
    <%= render :partial => 'songs/like_button', :locals => {:song => song} %>
    <%= render :partial => 'songs/likes', :locals => {:song => song} %>
  </p>
</li>

views/songs/_like_button.html.erb

<% if current_user.voted_on?(song) %>
  <%= link_to "Unlike", unlike_song_path(song), :method => :post, :remote => true %>
<% else %>
  <%= link_to "Like", like_song_path(song), :method => :post, :remote => true %>
<% end %>

views/songs/_likes.html.erb

<%= song.votes.count %>

views/songs/like.js.coffee

$("p.pull-right").html('<%= render :partial => "songs/like_button", :locals => {:song => song} %><%= render :partial => "songs/likes", :locals => {:song => song} %>');

controllers/songs_controller.rb

def like
  begin
    @vote = current_user.vote_for(@song = Song.find(params[:id]))
    @vote.save
    respond_with @song.user, :location => user_music_path(@song.user)
  rescue ActiveRecord::RecordInvalid
    redirect_to @song
  end
end

And as mentioned earlier, the :like action worked perfectly before I starting using AJAX. I've also added respond_to :html, :js to my songs_controller. And the error I get when I try to like the song is ActionView::Template::Error (undefined local variable or method "song" for #<#<Class:0x000001028de9d0>:0x00000106ecd9f0>):

  • 写回答

2条回答 默认 最新

  • perhaps? 2014-01-25 19:47
    关注

    Where you have

    <a href="<%= song.audio %>"><%= song.name %></a>
    

    try instead

    <a href="<%= @song.audio %>"><%= @song.name %></a>
    

    And do the same with your link_to paths and your render calls.

    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件