Ruby on Rails Thursday, September 4, 2014

Hi all,


Say I have an article class that has one main tag, but can also be
associated with multiple secondary tags. Something like schema listed
below. How can I implement the scope method below?


Basically I want one method where I can return ALL articles related to a
tag, regardless of whether it is a primary tag relationship or secondary
tag relationship.


Many Thanks!


class Article < ActiveRecord::Base
belongs_to :primary_tag,
:class_name => "Tag"

has_many :secondary_tag_listings

has_many :secondary_tags,
:through => :secondary_tag_listings,
:class_name => "Tag"

scope :all_with_tag, lambda { |tag_name|
# TODO: how to find all with either primary OR secondary tags
# as tag_name?
}
end




class SecondaryTagListings < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end




class Tag < ActiveRecord::Base
has_many :primary_articles,
:class_name => "Article"

has_many :secondary_tag_listings

has_many :secondary_articles,
:through => :secondary_tag_listings,
:class_name => "Article"
end

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/aced24f771ed6171143cc3dae41231b4%40ruby-forum.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment