如何在索引之前调用方法和从模型中调用new

时间:2014-02-19 21:40:30

标签: ruby-on-rails ruby ruby-on-rails-3

我的模型中有一个方法,

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参数传递给方法?

1 个答案:

答案 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