views:

204

answers:

3

In my application, Users can start and participate in Discussions. They can also Tag Discussions; when they do so, a Tag is created containing the name of the tag (if it didn't already exist), and a Tagging, which remembers which User tagged which Discussion with what Tag, is created too.

So inside the Discussion model we have this:

has_many :taggings
has_many :tags, :through => :taggings

I'm trying to create an easy way to retrieve all the Tags on a Discussion from one User. Ideally, named_scopes would be used judiciously to keep things nice and clean. I think it should look something like this:

tags = @discussion.tags.from_user(@user)

Writing this named_scope inside the Tag class is turning out to be very difficult. What should it look like? Do I need to join it with the Taggings table somehow?

A: 

Maybe this will do it. Not named_scope solution though:

tags = @discussion.taggings.find_by_user(@user).map(&:tag)

Not sure if you need to use taggings.find_by_user_id(@user.id) here. When that is done, you'll be left with an array which includes the taggings on given discussion by given user. Map that array to taggings.tag-model (I guess your Tagging model belongs_to a Tag).

Thorbjørn Hermansen
A: 

I haven't had chance to test this, but I think it might work:

class Discussion < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :discussion
  belongs_to :tag  
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :discussions, :through => :taggings

  named_scope :by_user do
    def named(user) do
      Tagging.find_by_user_and_discussion(user, discussion).tags
    end 
  end
end

Use it like this:

tags = @discussion.tags.by_user.named(@user)
John Topley
+1  A: 

You do need to join it with the taggings table somehow. Here's how:

class Tag < AR::Base
  named_scope :from_user, lambda { |user| 
    { :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] } 
  }
end
Ian Terrell