【问题标题】:How to call method before index and new from model如何在索引之前调用方法并从模型中调用新方法
【发布时间】:2023-03-15 22:19:01
【问题描述】:

我的模型中有一个方法,

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

【问题讨论】:

  • 请您能更好地解释一下您想要做什么吗?
  • 但我想将 current_user 参数传递给方法
  • @HrishikeshSardar current_user 是在哪里以及如何创建的?它是在另一个before_filter 中创建的,是否设置为实例变量(如@current_user)?

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


【解决方案1】:

您可以将 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

【讨论】:

  • 我想在模型中保留兴趣方法。
  • @HrishikeshSardar 我想出了一个更简单的方法并更新了我的答案。
  • 在 Rails 3 中没有回调 ActionMaler::Base,所以它没有在 before_action 上找到方法
  • @HrishikeshSardar 我很抱歉。我在 Rails 4 上开发了我的解决方案。如果需要,您可以编辑我的答案并将其恢复为旧解决方案。
猜你喜欢
  • 2023-03-10
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多