以下是我尝试在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中使用的模型,所以我不确定需要什么修复。谢谢。学家
答案 0 :(得分:3)
你的三元组中有一些错误:
include?
而不是include
?
if
也不需要end
image_path
不接受两个参数(仅保留网址)所以试试这个:
<% @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 %>