开发者

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 Us开发者_运维知识库er < 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 !


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜