how to avoid duplicates in a has_many :through relationship?

Simpler solution that’s built into Rails: class Blog < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :readers, :through => :blogs_readers, :uniq => true end class Reader < ActiveRecord::Base has_many :blogs_readers, :dependent => :destroy has_many :blogs, :through => :blogs_readers, :uniq => true end class BlogsReaders < ActiveRecord::Base belongs_to :blog belongs_to :reader end Note adding the :uniq … Read more

Rails Associations – has_many => :through – but same model

That was an interesting question. I just created a working app for your use case. post.related_posts will give you all posts related from post, while post.inverse_related_posts will give you all posts related to post. Here’s what my models look like: class Post < ActiveRecord::Base has_many :related_posts_association, :class_name => “RelatedPost” has_many :related_posts, :through => :related_posts_association, :source … Read more

Rails: has_many through with polymorphic association – will this work?

You have to do: class Person < ActiveRecord::Base has_many :events has_many :meals, :through => :events, :source => :eventable, :source_type => “Meal” has_many :workouts, :through => :events, :source => :eventable, :source_type => “Workout” end This will enable you to do this: p = Person.find(1) # get a person’s meals p.meals.each do |m| puts m end # … Read more