4

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 !

4 Answers 4

10

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 :)...

1
3

It is possible with the Tenacity gem: https://github.com/jwood/tenacity

We've been using it in production for a few months and it's working very well.

1
0

Was actually after the same solution. wrote this https://rubygems.org/gems/mongo_mysql_relations to make it easier - but it is basically the same solution as offered above, but less manual.

Github is at https://github.com/eladmeidar/MongoMysqlRelations

-2

No it's not possible. ActiveRecord is expecting the association is to an AR object. You used to be able to relate Mongoid to AR, but it doesn't work either now.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.