Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-921

referenced_in/belongs_to on the same collection. Upgrade issue beta20 - 2.0.1.

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.3.1
    • Affects Version/s: None
    • Component/s: None

      I am currently having a problem when upgrading from version beta 20 to
      2.0.1

      class User 
        include Mongoid::Document 
        include Mongoid::Timestamps 
        embeds_many :my_relations, 
                :class_name => 'Relation' 
      end 
      class Relation 
        include Mongoid::Document 
        include Mongoid::Timestamps 
        # tried changing this to belongs_to 
        referenced_in :target, 
                :class_name => 'User' 
        embedded_in :owner, 
                :class_name => 'User', 
                :inverse_of => :my_relations 
      end 
      

      Some how this does not work even after changing the referenced_in
      macro to 'belongs_to'.
      In the relation model I am trying to keep track to which other user is
      the current user referenced.
      Every time I try to create a new relation I get an error
      NoMethodError: undefined method `first' for #<Relation:0x7f325a0f3a78>
      Any ideas as to what is going wrong..

      It seems that there is no way out of the box to have one sided relationship from embedded object, on its own collection


      Solution.... which i have right now..
      I have solved this currently by removing referenced_in macro from relation model and adding a field target_id, and following methods for it.
      def target=(user)
      self.target_id = user.id
      end

      def target
      @target ||= User.find(target_id)
      end
      with this the code worked..

      uf = User.create!(:nickname =>'first')
      ul = User.create!(:nickname =>'last')
      uf.my_relations.push(Relation.new(:state => 'first', :target => ul))


      Nick also had mentioned a solution on google group... which is as below..

      The problem seems to be with the "target" association in Relation. If I set
      a relation's "target", the error occur. However, if I set a relation's
      "target_id", the error doesn't occur. Until this bug is fixed, you can use
      that as a workaround. Eg:
      u1 = User.first
      u2 = User.new
      u2.my_relations.create :target_id => u1.id
      u2.save

      Discussion on google group..
      http://groups.google.com/group/mongoid/browse_thread/thread/fadd08bb1d0f5bc1

            Assignee:
            durran Durran Jordan
            Reporter:
            greenman greenman
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: