我在哪里放置使用params的rails方法/范围?

时间:2013-08-30 18:21:39

标签: ruby-on-rails

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

考虑到它是一个从数据库中获取数据的过滤器,我认为最好进入模型,但我发现有关模型中的参数是否正确或不良实践的相互矛盾的信息。此外,我无法让它在模型中使用param存在。

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

这是我的代码:

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 %>

1 个答案:

答案 0 :(得分:0)

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

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

 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
相关问题