1

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 ?

Spyros
  • 46,820
  • 25
  • 86
  • 129
  • What about using virtual attributes? I mean use a virtual attribute in the Clan model named user_id and sets the virtual attribute on creating the Clan. The virtual attribute will be accessible from self.user_id – mohamagdy Feb 26 '12 at 22:03

1 Answers1

4

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

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.

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

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • nice solution thanx :) Just a notice that it also needs an 'attr_accessor :leader' here. – Spyros Feb 26 '12 at 22:29
  • @SpyrosP: Don't use `attr_accessor`. leader should be saved as an association on the clan. See my updated answer. – Ryan Bigg Feb 27 '12 at 01:23
  • ahh, i see what you mean, but i don't really want to have a leader_id. I actually save my members through another model(clan_membership), because there are other ranks as well. – Spyros Feb 27 '12 at 01:45