我是一名铁路4初学者,他整天都困惑于这个问题。 我想从用户表中提取位置以在api中使用,但我不断收到此错误:
#< User :: ActiveRecord_Relation的未定义方法`location':0x007f7082b4cfe0>
这是我的代码:
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
以下是我的观点:
<% @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>
答案 0 :(得分:1)
位置未在@users中定义(因为是一组用户),但在用户中。你必须做这样的事情:
@users = User.all
@users.each do |user|
if session[:user_id]
origin = current_user.location
destination = user.location
etc