简体   繁体   English

如何在模型中调用控制器方法

[英]How to call controller method in model

I have a user model which has association with groups.我有一个与组关联的用户模型。 The relation is given below关系如下

class User < ActiveRecord:;Base
  has_many :groups
end
class Group < ActiveRecord::Base
  belongs_to :user
  scope :user_groups, lambda { where(arel_table(:user_id).eq(@current_user.id) }
end

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find(session['entity.user']) if session['entity.user']
  end
end

I want to filter current_user groups in my select_tag in group index page.我想在组索引页面的 select_tag 中过滤 current_user 组。

How to achieve this?如何做到这一点?

You should not access to this data inside the model (it is violating the MVC). 您不应在模型内部访问此数据(它违反了MVC)。 You would be better to pass it as an argument to the scope: 您最好将其作为范围的参数传递:

scope :user_groups, 
           lambda { |user| where(arel_table(:user_id).eq(user.try(:id) || user) }

And call it like this: 并这样称呼它:

User.user_groups(@current_user) # or you can pass @current_user.id, still works

Note : You can pass either an id (Integer) or a User Object to the user_groups lambda. 注意 :您可以将id(整数)或用户对象传递给user_groups lambda。

Sometimes you might need to check the current_user in model. 有时您可能需要检查模型中的current_user。 So in current user method set following: 因此,在当前用户方法中设置以下内容:

 ActiveRecord::Base.current_user = @current_user

This will helps in checking current_user in any model you define in future. 这将有助于检查您将来定义的任何模型中的current_user。

Saving value as class variable will not help as these class variables are shared between requests, although in development mode is this deactivated (see config.cache_classes = true|false), so another request can rewrite your variable value to its own value before you will read the value in model.将值保存为类变量将无济于事,因为这些类变量在请求之间共享,尽管在开发模式下这是停用的(请参阅 config.cache_classes = true|false),因此另一个请求可以在您将变量值重写为它自己的值之前读取模型中的值。 As already mentioned, it is against MVC.如前所述,它反对 MVC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM