User HasOne ActiveToken, HasMany Tokens, how to setup in Rails?

Posted by viatropos on Stack Overflow See other posts from Stack Overflow or by viatropos
Published on 2010-05-09T21:29:14Z Indexed on 2010/05/09 23:08 UTC
Read the original article Hit count: 157

I have two simple models:

class User < ActiveRecord::Base
  has_many :tokens

  # has_one doesn't work, because Token already stores
  # foreign id to user...
  # has_one :active_token, :class_name => "Token"

  # belongs_to doesn't work because Token belongs to 
  # User already, and they both can't belong to each other
  # belongs_to :active_token, :class_name => "Token"
end

class Token < ActiveRecord::Base
  belongs_to :user
end

I want to say "User has_one :active_token, :class_name => 'Token'", but I can't because Token already belongs_to User. What I did instead was just manually add similar functionality to the user like so:

class User < ActiveRecord::Base
  has_many :tokens
  attr_accessor :active_token

  after_create :save_active_token
  before_destroy :destroy_active_token

  # it belongs_to, but you can't have both belongs_to each other...
  def active_token
    return nil unless self.active_token_id
    @active_token ||= Token.find(self.active_token_id)
  end

  def active_token=(value)
    self.active_token_id = value.id
    @active_token = value
  end

  def save_active_token
    self.active_token.user = self
    self.active_token.save
  end

  def destroy_active_token
    self.active_token.destroy if self.active_token
  end
end

Is there a better way?

© Stack Overflow or respective owner

Related posts about active-record

Related posts about ruby-on-rails