Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord and Mogoid::Document : associations

I have one model based on ActiveRecord and another based on a Mogoid::Document. Is that possible to do an association together ?

For Example, the 2 models :

class User < ActiveRecord::Base
  has_one :avatar, :dependent => :destroy
end

class Avatar
  include Mongoid::Document
  field :file_name
end

And retrieve User's avatar like this :

@user.avatar.file_name

Thanks !

like image 651
Tibal Avatar asked Dec 21 '22 21:12

Tibal


1 Answers

You won't be able to use ActiveRecord relations.

You still can link the two objects using instance methods like this :

class User < ActiveRecord::Base

  def avatar
    Avatar.where(:user_id => self.id).first
  end

  def avatar=(avatar)
    avatar.update_attributes(:user_id => self.id)
  end

end

It would be interesting to encapsulate this in a module :)...

like image 126
Nicolas Blanco Avatar answered Dec 24 '22 11:12

Nicolas Blanco