This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Easy Join Table Conditions
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
For an application with anything above a moderate level of domain complexity it’s quite likely that you’ve had to perform a query utilizing a join table:
1234567891011
classArticle < ActiveRecord::Base belongs_to :userendclassUser < ActiveRecord::Base has_many :articlesend# Get all the users that have published articlesUser.find(:all, :joins => :article,:conditions => ["articles.published = ?", true])
It always makes me feel slightly embarrassed to have to resort to using String snippets to specify my query logic, and this little bit is no exception. Well, now we can specify conditions on a join table in a more concise manner:
123
# Get all the users that have published articlesUser.find(:all, :joins => :article,:conditions => { :articles => { :published => true } })
Note how you’re able to specify the join-table conditions as a hash whose key corresponds to the table or association name of the join table? You can now let Rails worry about forming the correct SQL condition even across complex joins.
However, don’t let the ease of this feature make you use it over a properly associated domain-model. For instance, this join query:
123
# Get all articles for a given userArticle.find(:all, :joins => :user,:conditions => { :users => { :id => @user.id } })