Pergunta

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 !

Foi útil?

Solução

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

Outras dicas

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.

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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top