使用Ajax,Rails 4在partials中渲染局部变量

时间:2015-09-09 02:23:46

标签: jquery ruby-on-rails ruby ajax ruby-on-rails-4

我无法在Ajax调用之后将局部变量显示在partials中。这是我的设置:

查看 - index.html.erb

<% @artists.each do |artist| %>
  <div class="index_follow_button">
    <%= render "partials/index_follow_button", :artist => artist %>
  </div>
<% end %>

查看 partials / _index_follow_button.html.erb

<% if fan_signed_in? %>
  <% if fan_signed_in? && current_fan.following_artist?(artist) %>
    <%= button_to "unfollow", artist_relationship_path(artist, current_fan.artist_relationship_id(artist)), method: :delete, remote: true %>
  <% elsif fan_signed_in? %>
    <%= form_for(ArtistRelationship.new, url: artist_relationships_path(artist), remote: true) do |f| %>
      <%= f.submit "follow" %>
    <% end %>
  <% end %>
<% end %>

查看 - follow_button.js.erb

$('.index_follow_button').html('<%=  escape_javascript(render :partial => 'partials/index_follow_button.html.erb', :locals => {:artist => artist}) %>');

我认为这是错误的地方

控制器 - relationships_controller.rb

def create
  @relationship = ArtistRelationship.new
  @relationship.fan_id = current_fan.id
  @relationship.artist_id = Artist.friendly.find(params[:artist_id]).id
  @artist = Artist.friendly.find(params[:artist_id])
  if @relationship.save
    respond_to do |format|
      format.html { redirect_to (:back) }
      format.js { render :action => "follow_button" }
    end
  else
    redirect_to root_url
  end
end

def destroy
  current_fan.unfollow_artist(Artist.friendly.find(params[:artist_id]))
  @artist = Artist.friendly.find(params[:artist_id])
  respond_to do |format|
    format.html { redirect_to (:back) }
    format.js { render :action => "follow_button" }
  end
end

在索引页面中,部分使用:artist => artist完全正常显示,但同样的事情在JavaScript页面中没有发生,但我一直得到同样的错误 -

ActionView::Template::Error (undefined local variable or method `artist' for #<#<Class:0x3798df8>:0x6f43968>)

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

Artist是一个局部变量,但在你的js文件中它是未设置的(除非你留下一些代码)。而是尝试使用实例变量: follow_button.js.erb:

$('.index_follow_button').html('<%=  escape_javascript(render :partial => 'partials/index_follow_button.html.erb', :locals => {:artist => @artist}) %>');

在index.html.erb中,循环设置局部变量artist

看起来你还需要一种独特的方法让jquery解决相关元素。

<% @artists.each do |artist| %>
  <div class="index_follow_button" id="artist-<%= artist.id %>">
    <%= render "partials/index_follow_button", :artist => artist %>
  </div>
<% end %>

然后再次改变follow_button.js.erb;这次使用新的id作为css定位器而不是类。

$('#artist-<%= @artist.id %>').html('<%=  escape_javascript(render 
  :partial => 'partials/index_follow_button.html.erb', 
  :locals => {:artist => artist}) %>'
);

答案 1 :(得分:0)

我认为您在follow_button.js.erb文件中错过了@artist变量。

$('.index_follow_button').html('<%= escape_javascript(render :partial => 'partials/index_follow_button.html.erb', :locals => {:artist => @artist}) %>');