我的模型中有一个方法,
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
我想在索引和新操作之前将此方法调用到我的 Controller 中,我该怎么做?
所有的模型和 Controller 都是不同的实体
如果我在 Controller 中使用 before_filter,我将如何将 current_user 参数传递给该方法?
最佳答案
您可以将 lambda(在本例中为 {@interests = Widget.interests current_user}
)传递给 before_action
以实现您想要的效果。
app/controllers/widgets_controller.rb
class WidgetsController < ApplicationController
before_action(only: [:show]) {@interests = Widget.interests current_user}
def show
# do something with @interests
end
end
app/models/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
关于ruby-on-rails - 如何在索引之前调用方法并从模型中调用新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21893071/