Question

Selecting records through :has_many :through association

Asked by: lawrenjn

I have the following models, where `favorites` acts as a join table for my `users` to store their favorite `items`:

class User < ActiveRecord::Base
  :has_many :favorites
  :has_many :items, :through => :favorites
end

class Item < ActiveRecord::Base
  :has_many :favorites
  :has_many :users, :through => :favorites
end

class Favorite < ActiveRecord::Base
  :belongs_to :user    # foreign key user_id
  :belongs_to :item    # foreign key item_id
end

I want to do one query (find) that lists every item and has some sort of "flag" on each to show whether or not it's a favorite of the current user.  This SQL query is perfect at performing this:

"SELECT items.*, favorites.id AS fid FROM items LEFT JOIN favorites ON favorites.item_id=items.id AND favorites.user_id=#{@current_user.id}"

It returns every row in the items table and then has NULL for fid where the item is NOT a favorite of the current user.  This is what I want, so that in the partial that displays all items I can simply know by the presence of a non-null fid whether an item is already a favorite of the user.  

I cannot seem to reproduce this "the Rails Way".

I have tried:

Item.find :all, :joins => [ 'users', 'favorites' ], :conditions => [ 'favorites.user_id = #@current_user.id}"]

I believe that doesn't work because it does an INNER JOIN, not a LEFT JOIN and so eliminates items that are not in fact favorites of the current user, so I tried this next thing (again not very railsy, but thinking it would work via brute force at least):

Item.find :all, :joins => [ "LEFT JOIN favorites ON favorites.item_id = item.id" ], :conditions => [ 'favorites.user_id = #@current_user.id}"]

This similarly did not work and returned only the items that ARE favorites of the current user.  Apparently ActiveRecord is too smart and is "realizing" that I want only the items that are user favorites, but it's wrong!

What am I missing?

John

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-26 at 10:36:12ID24268287
Tags

has_many

,

through

,

ruby

,

rails

,

join

,

model

Topics

RubyOnRails

,

Ruby Scripting Language

Participating Experts
1
Points
500
Comments
2

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Foreign keys
    I would like to know how to specify foreign keys and indexes when creating a table. Please provide me with an example. Also when creating a table, how do I default the date field to now() so that it provides a current date, every time a record is entered. Finally I have a B...
  2. Trying to grasp INNER JOIN
    I have gotten to the stage where I need to start using INNER JOIN but I can't get my brain to rap around this query format. Basically what I want to do is this: I have table one: SoftwareInventory with fields: ClientID FileID InstanceKey (primary key) The ...
  3. Bidirectional associations between records
    How can I make a bidirectional association between two record types in the same unit? For example, I have TGrid containing an array of TCell's but every TCell might contain an inner TGrid: type TGrid = record Cells: array of TCell; ... end; TCell = record InnerGr...
  4. INNER JOIN using LINQ
    Hi, How to write the below query in LINQ select * from Booking inner join bookingoutcome on booking.uid = bookingoutcome.bookinguid and bookingoutcome.statusflag ='a' Thanks in advance Regards, Samsudeen B
  5. Rails: has_many :through | sorting on the :through
    I am trying to do something I can't find documentation on. I can do something close as a SQL string so i know it's possible, I just would like the Rails way to do it. I have 2 (tableA and tableB) tables and a third table (links) for linking the two together. It's not a sim...
  6. Foreign key column name matches model name
    If Rails is "picky" about the way things are named, then I don't even want to begin to think about what I am....but anyhow, here's the question: I'm new to Ruby / Ruby on Rails and am creating my first app just to play around. The convention that I've used for yea...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: wesgarrisonPosted on 2009-04-05 at 21:07:53ID: 24074302


# I used authors with has_many books, instead of Items
 
>> Author.find(:all)
  SELECT * FROM `authors` 
 
# Using :joins with an association symbol gives INNER JOIN
>> Author.find(:all, :joins => :books)
  SELECT `authors`.* FROM `authors` INNER JOIN `books` ON books.author_id = authors.id 
 
# Using :joins with a string uses that string as the join
>> Author.find(:all, :joins => "LEFT JOIN `books` ON books.author_id = authors.id")
  SELECT `authors`.* FROM `authors` LEFT JOIN `books` ON books.author_id = authors.id 
 
# Now, we need to grab the books.id using :select
>> result = Author.find(:all, :joins => "LEFT JOIN `books` ON books.author_id = authors.id", :select => "authors.*, books.id as has_book")
  SELECT authors.*, books.id as has_book FROM `authors` LEFT JOIN `books` ON books.author_id = authors.id 
 
result.first.has_book
  # => 12312443 (the books.id)
 
result.last.has_book
  # => nil
 
# Lazy answer: find_by_sql   :-)

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window

 

by: lawrenjnPosted on 2009-04-09 at 12:30:11ID: 31563143

I actually deemed that the issue was in how i was orchestrating my SQL query, which worked sometimes and not others.  It turns out that if I put the user_id condition in :conditions (or in the SQL WHERE clause), it didn't work, but if I put it in the :joins or (JOIN..ON) clause, it did, so even my SQL in my question is not correct and will not yield a list of all "items" with the user_id left NULL for non-compliant users, so:

SELECT ... LEFT JOIN users ON favorites.item_id=items.id AND favorites.user_id = 22 WHERE...                     works, while

SELECT ... LEFT JOIN users ON favorites.item_id=items.id WHERE favorites.user_id = 22 AND...                     does not

This basic thing can be reproduced using :joins => 'LEFT JOIN ....ON...AND' and leaving the user_id stipulation out of the :conditions part of the hash as well.  Thank you for looking at this.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...