2013-08-30 43 views
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 %> 

回答

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 
+0

我可以在我的主頁上使用'fetch_data'作爲鏈接方法嗎?恩。 '<%= events.fetch_data.size%>'? – BHOLT

+0

並非如此,但你可以初始化,然後使用 –

+0

這個初始化名副其實。我之前有過初始化工作,但我無法在主頁上獲得準確的'.size'。我會嘗試使用。是否有理由將fetch_data更好地分成兩個動作,而不是將其保留在索引中,因爲我只在那裏使用它? – BHOLT

相關問題