新手问题 请教关于 scope 的一段代码,有点疑惑!

stephen · 2014年09月16日 · 最后由 Victor 回复于 2014年09月16日 · 1715 次阅读

改改,添加上下文 Finding nearby check-ins

Let’s create a method for finding nearby check-ins. PostGIS has a function named ST_DWithin which returns true if two locations are within a certain distance of each other. In app/models/checkin.rb, add the following to the top of the class:

class Checkin < ActiveRecord::Base
  scope :nearby_to,
    lambda { |location, max_distance|
      where("ST_DWithin(location, ?, ?) AND id != ?", checkin.location, max_distance, checkin.id)
    }

In app/controllers/checkins_controller.rb, add the following:

def show
  @checkin = Checkin.find(params[:id])
  @nearby_checkins = Checkin.nearby_to(@checkin, 1000)

In app/views/checkins/show.html.erb, add the following just before the links in the bottom:

<h2>Nearby check-ins</h2>
<ul>
  <% @nearby_checkins.each do |checkin| %>
    <li><%= link_to checkin.title, checkin %></li>
  <% end %>
</ul>

It now shows all nearby checkins. Try adding a couple more based on your current location and see it in action. 在这段代码里

class Checkin < ActiveRecord::Base
  scope :nearby_to,
    lambda { |location, max_distance|
      where("ST_DWithin(location, ?, ?) AND id != ?", checkin.location, max_distance, checkin.id)
    }
end

这个 checkin 变量哪里来的?还有 location 这个传入参数还是没使用到?

这代码是错的

需要 登录 后方可回复, 如果你还没有账号请 注册新账号