更改image_tag Rails上的源属性

时间:2017-07-10 18:51:49

标签: ruby-on-rails

以下是我尝试在Rails中切换图像:

控制器的更新操作:

  def update
    @user = current_user
    @peaks = Peak.all 
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to user_path }
        format.js { render action: :show, format: :js }
      else
         format.html { redirect_to root_path }
      end
    end
  end

和.js.erb文件:

<% @peaks.each do |peak|%>
$('#<%= if @user.peaks.include(peak)?  peak.id : ""
    end %>').attr( "src" , "<%= image_path "badges/chevron-10.png", :id => peak.id %>" );
<% end %>

但是,我在服务器输出中收到以下错误:

ActionView::Template::Error (wrong argument type Peak (expected Module)):
3:
4: <% @peaks.each do |peak|%>
5: $('#<%= if @user.peaks.include(peak)?  peak.id : ""
6:         end %>').attr( "src" , "<%= image_path "badges/chevron-10.png", :id => peak.id %>" );
7: <% end %>

Peak是app中使用的模型,所以我不确定需要什么修复。谢谢。学家

1 个答案:

答案 0 :(得分:3)

你的三元组中有一些错误:

  1. 该方法为include?而不是include
  2. 您必须在条件与?
  3. 之间添加空格
  4. 您既不需要if也不需要end
  5. image_path不接受两个参数(仅保留网址)
  6. 所以试试这个:

    <% @peaks.each do |peak|%>
      $('#<%= @user.peaks.include?(peak) ? peak.id : "" %>').attr("src", "<%= image_path("badges/chevron-10.png") %>");
    <% end %>
    

    上面的代码将消除您当前的错误,但如果三元评估为false并返回""(因为DOM中的元素不匹配id = ""),则可能会失败。

    为避免这种情况,我建议您跳过三元组并使用常规if语句,如下所示:

    <% @peaks.each do |peak| %>
      <% if @user.peaks.include?(peak) %>
        $('#<%= peak.id %>').attr("src", "<%= image_path("badges/chevron-10.png") %>");
      <% end %>
    <% end %>