0

我有一个与组关联的用户模型。关系如下

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

我想在组索引页面中的 select_tag 中过滤 current_user 组。

如何做到这一点?

4

2 回答 2

1

您不应该在模型内部访问这些数据(它违反了 MVC)。您最好将其作为参数传递给范围:

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

并这样称呼它:

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

注意:您可以将 id(整数)或用户对象传递给user_groupslambda。

于 2013-01-11T15:07:50.873 回答
0

有时您可能需要检查模型中的 current_user。所以在当前的用户方法中设置如下:

 ActiveRecord::Base.current_user = @current_user

这将有助于检查您将来定义的任何模型中的 current_user。

于 2013-01-11T15:08:36.403 回答