Rails:acts-as-taggable-on: Using tagged_with on a

2019-06-14 02:29发布

Lets say I have a Model A which has a 1 to 1 association with Model B. Model B is set to 'acts_as_taggable'. I would like to return an active record relation that selects all A instances who's B attribute is tagged_with a certain string. It would look something like: A.where('b.tagged_with = ?', 'some_tag')

I found this SO question, but i'm interested in getting an active record relation back so only the 2nd solution is applicable and I can't get it to work. How can I get back active record relations so I can call other query params methods on it ie. A.b_tagged_with('tag').where(...) where b_tagged_with is a named scope

1条回答
一夜七次
2楼-- · 2019-06-14 03:01

to answer my own question, my scope definition in A looks like this:

    scope :tagged_with, lambda { |tag|
    {
        :joins => "INNER JOIN taggings ON taggings.taggable_id = as.b_id\
                   INNER JOIN tags ON tags.id = taggings.tag_id AND taggings.taggable_type = 'B'",
        :conditions => ["tags.name = ?", tag]
    }
  }

What this says is return all A models whose b members are associated with a tagging if that taggings' tag association has a 'name' value equal to the param we passed in. In this example B 'acts_as_taggable', A doesn't. This allows me to do:

a = A.new
b = B.new
b.tag_list = ['tag1', 'tag2', 'tag3']    
a.b = b
new_a = A.tagged_with('tag1').ordered(...
#At this point new_a.last == a
查看更多
登录 后发表回答