arsk
arsk

Reputation: 25

"Undefined method where" error in query

I have spent the last day trying different things and searching the internet on the answer but I am just plain stuck.

I have a rails app (4.0) which logs PB's made in the gym for different lifts.

I would like to display the highest weight for 1 rep, 3 reps and 5 reps.

My controller looks like this.

@history = current_user.workouts.order("weight DESC","reps DESC").group_by(&:lift)

The code in my view is then as follows...

<% @history.each do | lift, workout | %>
  <% name = lift[lift].downcase.gsub(/[ &]/,'') %>
  <tr>
    <td><%= link_to lift[lift], send("workouts_lift_#{name}_path") %></td>
    <td><%= workout.where(:reps => 1).max_by(&:weight).weight %> kg</td>
    <td><%=  workout.where(:reps => 3).max_by(&:weight).weight %> kg</td>
    <td><%=  workout.where(:reps => 5).max_by(&:weight).weight %> kg</td>
  </tr>
<% end %>

I keep getting a error for the where method. I'm unclear as to what the problem is as I can get it to work in the rails console using

user.workouts.where(:reps=> 1).where(:lift => "Snatch")

Upvotes: 1

Views: 179

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

In your view, the workout variable that is yielded in the each block is an instance of the Workout class, not the class itself. ActiveRecord query methods such as where are only available on classes or relationships, hence the error. Without knowing the underlying architecture of your models and relationships, it's hard to say exactly what you can do to fix it though.

Upvotes: 2

Related Questions