在after_createfilter中获取当前用户
我知道在模型中获取current_user是个坏主意。 我也知道有办法(使用Thread)。 但是,我不想这样做(这当然是一个坏主意),所以我想对以不同的方式实现这一点有意见。
用户可以创建一个战队,在创建战队时,他必须是领导者。 Clan模型是:
class Clan < ActiveRecord::Base after_create :assign_leader # the person who created the clan is the leader def assign_leader self.clan_memberships < ???, :role => 'leader') end end
我知道我可以在控制器中创建成员资格。 但是,我喜欢filter充当交易,我更喜欢这个filter。 但是,这里真的有一种正确的,非“黑客”的做法吗?
在控制器中分配领导者:
@clan.leader = @clan @clan.save
然后你的模型看起来像这样:
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
代码更assign_leader
。
当然,您需要将leader_id
作为字段添加到您的clans
表中。