Reputation: 101
the following is my attempt to switch images in Rails :
The controller's update action:
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
and the .js.erb file:
<% @peaks.each do |peak|%>
$('#<%= if @user.peaks.include(peak)? peak.id : ""
end %>').attr( "src" , "<%= image_path "badges/chevron-10.png", :id => peak.id %>" );
<% end %>
However, I'm getting the following error in the server output:
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 is a model used in the app, so I am unsure as to what fix is necessary. Thanks. J.
Upvotes: 0
Views: 43
Reputation: 10497
You have a few errors in your ternary:
include?
not include
?
if
nor end
image_path
doesn't accept two arguments (keep only the url)So try this instead:
<% @peaks.each do |peak|%>
$('#<%= @user.peaks.include?(peak) ? peak.id : "" %>').attr("src", "<%= image_path("badges/chevron-10.png") %>");
<% end %>
The above code will get rid of your current error, but could fail if the ternary evaluates to false
and returns ""
(because no element in the DOM will match id = ""
).
To avoid this i will recommend skipping the ternary and using a regular if
statement, like this:
<% @peaks.each do |peak| %>
<% if @user.peaks.include?(peak) %>
$('#<%= peak.id %>').attr("src", "<%= image_path("badges/chevron-10.png") %>");
<% end %>
<% end %>
Upvotes: 3