The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
What's New in Edge Rails: Easy Join Table Conditions

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
rwdaigle

Posts: 312
Nickname: rwdaigle
Registered: Feb, 2003

Ryan is a passionate ruby developer with a strong Java background.
What's New in Edge Rails: Easy Join Table Conditions Posted: Jul 7, 2008 1:57 PM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by rwdaigle
Latest Posts From Ryan's Scraps

Advertisement

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:

1
2
3
4
5
6
7
8
9
10
11
class Article < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :articles
end

# Get all the users that have published articles
User.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:

1
2
3
# Get all the users that have published articles
User.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:

1
2
3
# Get all articles for a given user
Article.find(:all, :joins => :user,
  :conditions => { :users => { :id => @user.id } })

is more appropriately represented as:


@user.articles

tags: ruby, rubyonrails

Read: What's New in Edge Rails: Easy Join Table Conditions

Topic: I'm doing the friendfeed thing Previous Topic   Next Topic Topic: Twitter Litter

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use