rails has_many :through – Is it possible to have a conditions in the through table?

Jochen’s link has a good solution – but :conditions is deprecated and the :conditions => [‘event_users.active = ?’,true] bit just doesn’t seem very rails. Try this: has_many :game_users has_many :game_likes, -> { where like: true }, class_name: ‘GameUser’ has_many :liked_games, :through => :game_likes, class_name: ‘Game’, :source => :game

Rails RSpec Tests for a has_many :through Relationship

I would recommend checking out a gem called Shoulda. It has a lot of macros for testing things like relationships and validations. If all you want is to test that the has_many relationship exists, then you could do the following: describe Post do it { should have_many(:categories) } end Or if you’re testing a has_many … Read more

Rails – Sort by join table data

I would suggest to avoid using default_scope, especially on something like price on another table. Every time you’ll use that table, join and ordering will take place, possibly giving strange results in complex queries and anyway making your query slower. There’s nothing wrong with a scope of its own, it’s simpler and it’s even clearer, … Read more

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)