ruby-on-rails - 如何在索引之前调用方法并从模型中调用新方法

标签 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

我想在索引和新操作之前将此方法调用到我的 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/

相关文章:

ruby-on-rails - 目录 : Carrierwave Not Working/Saving to Database

ruby-on-rails - Heroku 推送错误 : "NameError: uninitialized constant Uglifier::VERSION" on rake assets:precompile

ruby-on-rails - 如何将行数组渲染到 &lt;textarea&gt;?

ruby-on-rails - 如何将自定义文本添加到成功 rspec 消息中

ruby-on-rails - ruby rails : How to add a form text field if the corresponding filed in the model doesn't exist?

ruby-on-rails - 编写一个全局方法,通过 current_user 设置 created_by 和 updated_by

ruby-on-rails - rails 4 : having a proxy model to combine multiple models

ruby-on-rails - 将 vendor/assets/javascripts 添加到我的有效 Assets 路线

ruby-on-rails-3 - 导轨 3 : How to get a custom restful member route without ID

ruby-on-rails - ruby on Rails - 如何在路线、 Controller 、 View 中建立关系?有很多,属于