我的模型中有一个方法,
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 :(得分: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