Joliet
Joliet

Reputation: 101

Change source attribute on image_tag Rails

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

Answers (1)

Gerry
Gerry

Reputation: 10497

You have a few errors in your ternary:

  1. The method is include? not include
  2. You must add a space between the condition and the ?
  3. You need neither if nor end
  4. 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

Related Questions