On Tue, Jan 12, 2010 at 1:03 PM, Philip Hallstrom <[email protected]> wrote:
>
> On Jan 12, 2010, at 9:46 AM, Steve Castaneda wrote:
>
>> Owners has_one :widget and Widgets belongs_to :owner.
>
> @owners = Owner.all(:conditions => 'widget_id IS NULL')
>
> Would do it.  Assuming that it's correct to say that if widget_id is null
> they have no widget -- this wouldn't catch instances where say an owner
> *had* widget, the widget was removed and the owners widget_id wasn't set
> back to null.

No, I don't think that this will work given the database schema described.

Widget belongs_to :owner
Owner has_one :widget

means that the widgets table has an owner_id colum , the owners table
doesn't have a widget_id field.

The has_one relationship is really just a has_many which adds a limit
of 1 to the query.

>
> @owners = Owner.all.reject{|o| o.widget.nil? }
>
> Would also do it.  This has the drawback that the DB is going to return
> *all* the owners and then filter them in ruby.  Won't be as speedy as the
> first option.

This will work, but as you point out it can be inefficient if there
are a lot of owners.

While it's possible to get this down to a single SQL query with the
given db design, using an outer join and a carefully crafted
conditions clause, it might be simpler just to reverse the
relationship, as long as there is really a 1-1 cardinality
relationship, it could just as well be

Owner belongs_to :widget
Widget has_one :owner

with the concommittant db table changes.

Then
@owners = Owner.all(:conditions => 'widget_id IS NULL')

would work.

-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply via email to