2014-02-19 27 views
1

我有一個方法,在我的模型,如何調用索引之前的方法和新的模式

def self.interests(user) 
    City.joins("INNER JOIN property_of_interests ON property_of_interests.city_id = cities.id").where(:property_of_interests => {:user_id => user}) 
end 

我想調用這個方法進入指數和新的行動之前,我的控制器,我怎麼能我能做到這一點?

而且所有的模型和控制器是不同的實體

如果我在控制器中使用的before_filter我將如何傳遞CURRENT_USER參數的方法嗎?

+0

你能更好地解釋你想做的事,好嗎? –

+0

也許使用'before_filter'(http://rails-bestpractices.com/posts/22-use-before_filter) – lurker

+0

但我想將current_user參數傳遞給方法 –

回答

3

您可以將lambda(在此例中爲{@interests = Widget.interests current_user})傳遞到before_action以實現您想要的效果。

應用程序/控制器/ widgets_controller.rb

class WidgetsController < ApplicationController 
    before_action(only: [:show]) {@interests = Widget.interests current_user} 

    def show 
    # do something with @interests 
    end 
end 

應用程序/模型/ widget.rb

class Widget < ActiveRecord::Base 
    def self.interests(user) 
    City.joins("INNER JOIN property_of_interests ON property_of_interests.city_id = cities.id").where(:property_of_interests => {:user_id => user}) 
    end 
end 
+0

我想在模型中保留興趣方法。 –

+0

@HrishikeshSardar我想出了一個更簡單的方法並更新了我的答案。 – franksort

+0

在rails 3中沒有回調ActionMaler :: Base,所以它沒有找到方法before_action –

相關問題