1
我有一个范围使用RubyGeocoder方法near
来按位置使用param[:searchCity]
来过滤事件。 param获取用户的地理位置,因此只显示附近的事件。我目前在我的events_controller
索引操作中工作,但我也需要在我的主页上调用它。我在哪里放置使用params的rails方法/范围?
考虑到它是一个从数据库中获取数据的过滤器,我认为最好在模型中使用,但是我发现在模型中有参数是好还是坏的信息是冲突的。另外,我无法在模型中使用参数。
什么是这样的最佳做法?我应该在哪里放置范围,模型,控制器,助手或其他地方?
这里是我的代码:
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 %>
我可以在我的主页上使用'fetch_data'作为链接方法吗?恩。 '<%= events.fetch_data.size%>'? – BHOLT
并非如此,但你可以初始化,然后使用 –
这个初始化名副其实。我之前有过初始化工作,但我无法在主页上获得准确的'.size'。我会尝试使用。是否有理由将fetch_data更好地分成两个动作,而不是将其保留在索引中,因为我只在那里使用它? – BHOLT