ActiveRecord and Mogoid::Document : associations

2019-04-10 12:06发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-04-10 12:42

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.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-10 12:50

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

查看更多
Anthone
4楼-- · 2019-04-10 12:53

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-04-10 12:54

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

查看更多
登录 后发表回答