1

我有一个使用 RubyGeocoder 方法的范围,near通过使用param[:searchCity]. 参数获取用户的地理位置,因此它只显示他们附近的事件。我目前在我的events_controller索引操作中使用它,但我还需要在我的主页上调用它。

考虑到它是一个从数据库中获取数据的过滤器,我认为最好进入模型,但我发现关于模型中的参数是好的还是不好的做法的信息相互矛盾。此外,我无法让它在存在参数的模型中工作。

这种事情的最佳做法是什么?我应该将范围、模型、控制器、助手或其他地方放在哪里?

这是我的代码:

Model:
class Event < ActiveRecord::Base
  # attr, validates, belongs_to etc here.
  scope :is_near, self.near(params[:searchCity], 20, :units => :km, :order => :distance) #doesn't work with the param, works with a "string"
end

Controller:
def index
  unless params[:searchCity].present?
    params[:searchCity] = request.location.city
  end

  @events = Event.is_near

  # below works in the controller, but I don't know how to call it on the home page
  # @events = Event.near(params[:searchCity], 20, :units => :km, :order => :distance)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @events }
  end
end

The line I'm calling in my home page that gets how many events are in the area
<%= events.is_near.size %>

编辑:使用 lambda 似乎有效。有什么理由我不应该这样做吗?

Model:
class Event < ActiveRecord::Base
  scope :is_near, lambda {|city| self.near(city, 20, :units => :km, :order => :distance)}
end

Controller:
def index
  @events = Event.is_near(params[:searchCity])
...

home.html.erb
<%= events.is_near(params[:searchCity]).size %>
4

1 回答 1

0

无法访问模型中的参数。参数是只存在于控制器和视图级别的东西。

所以最好的方法是在控制器中编写一些辅助方法来执行此操作。

 Class Mycontroller < ApplicationController
   before_action fetch_data, :only => [:index]

   def fetch_data
     @data = Model.find(params[:id])#use params to use fetch data from db 
   end

   def index

   end
于 2013-08-30T18:35:46.703 回答