在 after_create 过滤器中获取当前用户 [英] Fetch current user in after_create filter

查看:33
本文介绍了在 after_create 过滤器中获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在模型中获取 current_user 是个坏主意.我也知道有一种方法可以做到(使用 Thread).但是,我不想这样做(这当然是个坏主意),所以我想以不同的方式实现这一点.

i know that it's a bad idea to fetch the current_user in a model. I also know that there is a way to do it (with Thread). But, i don't want to do it this way(it's certainly a bad idea), so i would like to have an opinion on achieving this a different way.

用户可以创建氏族,创建氏族后,他必须是领导者.氏族模型是:

A user can create a clan, and upon creating it, he has to be the leader. The Clan model is :

class Clan < ActiveRecord::Base
    after_create :assign_leader

    # the person who created the clan is the leader
    def assign_leader
      self.clan_memberships << ClanMembership.new(:user_id => ???, :role => 'leader')
    end
end

我知道我可以在控制器中创建成员资格.但是,我喜欢过滤器作为交易,我非常喜欢这个过滤器.但是,这里真的有一种正确的、非黑客式"的方法吗?

I know i can just create the membership in the controller. However, i like that filters act as transactions and i would very much prefer a filter for this. But, is there really a correct, non 'hackerish' way of doing that here ?

推荐答案

在控制器中分配领导者:

Assign the leader in the controller:

@clan.leader = @clan
@clan.save

那么您的模型将如下所示:

Then your model would look like this:

class Clan < ActiveRecord::Base
  belongs_to :leader
  after_create :assign_leader

# the person who created the clan is the leader
def assign_leader
  self.clan_memberships.create(:user => self.leader)
end

这意味着您可以检查 clan.leader 的领导者,而不必查询另一个关联(例如 clan.memberships)来找出领导者是谁.它还可以使 assign_leader 中的代码更清晰.

This means then you could check clan.leader for the leader, rather than having to query another association such as clan.memberships to find out who that is. It also leads to cleaner code in assign_leader.

当然,您需要将 leader_id 作为字段添加到您的 clas 表中.

You will, of course, need to add leader_id as a field to your clans table.

这篇关于在 after_create 过滤器中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆