Ishaan Sehgal
Ishaan Sehgal

Reputation: 11

undefined method for active_record error

I am a rails 4 beginner who has been confused all day with this problem. I want to pull out the location from the user table to use in an api but I keep getting this error:

undefined method `location' for # <User::ActiveRecord_Relation:0x007f7082b4cfe0>

Here is my code:

def index
@users = User.all

if session[:user_id]
  origin = current_user.location    
  destination = @users.location
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{origin}&destinations=#{destination}"
result = open(url).read
parsed_result = JSON.parse(result)
distance_in_km = parsed_result['rows'][0]["elements"][0]["distance"]["text"]
@distance = distance_in_km
@duration =parsed_result['rows'][0]["elements"][0]["duration"]["text"]
else
  origin = "boston"
destination = "michigan"
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{origin}&destinations=#{destination}"
result = open(url).read
parsed_result = JSON.parse(result)
distance_in_km = parsed_result['rows'][0]["elements"][0]["distance"]["text"]
@distance = distance_in_km
@duration =parsed_result['rows'][0]["elements"][0]["duration"]["text"]
end
end

Here is my view:

<% @users.each do |user| %>
<tr>

 <td><%= user.name %></td> 
  <td><%= user.email %></td>
  <td><a href="/users/<%= user.id %>">Show</a> </td>   
  <td><a href="/users/<%= user.id %>/edit">Edit</a></td>
 <td><a href="/users/<%= user.id %>/destroy">Destroy</a></td>
  <td> Distance from you: <%=@distance%> km <br /> It should take you <%= @duration%> to drive there. </td>

</tr>

Upvotes: 1

Views: 87

Answers (1)

Papaya Labs
Papaya Labs

Reputation: 1089

location is not defined in @users (because is an array of users), but in user. You have to do something like this:

@users = User.all

@users.each do |user|
 if session[:user_id]
  origin = current_user.location    
  destination = user.location

etc

Upvotes: 1

Related Questions