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

Can you still keep accessor methods when using inverse_of: nil on the other side

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      Hi,

      I have a one sided has_and_belongs_to_many example similar to this:

      class Post
      has_and_belongs_to_many :tags, inverse_of: nil, index: true
      end

      class Tag

      1. you don't want this side to have post_ids since it could be 1000s of posts
        end

      I would still like to have the accessor methods on the Tag side. I started writing my own like this:

      def posts
      Posts.where(tag_ids: self.id)
      end

      def posts<< ps
      Post.collection.update(
      Post.any_in(_id: ps.collect

      {|p| p.id }).selector,
      {'$push' => {tag_ids: self.id}},
      {:multi => true}
      )
      end

      def posts= ps
      Post.collection.update(
      Post.any_in(_id: ps.collect{|p| p.id }

      ).selector,
      {'$set' => {tag_ids: self.id}},
      {:multi => true}
      )
      end

      But i realized there are a lot...plus callbacks for when a post is destroyed etc. So I thought maybe there was an easier way? For example maybe if I could just override the selector the rest would work normally.

      Thanks for any ideas!

            Assignee:
            Unassigned Unassigned
            Reporter:
            barmstrong Brian Armstrong
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: