On Jan 12, 2010, at 9:46 AM, Steve Castaneda wrote:

Owners has_one :widget and Widgets belongs_to :owner.  When creating a
new widget, I'm giving the option for the user to specify the owner by
using a drop down select. The select is populated by pulling a list of
owners.

What would be the best way to populate the select with owners who do not
have a widget?

I'm assuming my controller would look something like this for Widgets:

--
def new

 @widget = Widget.new
 @widgets = Widget.find(:all)
 @owners = Owners.find(:all, :conditions => '...this is where I go
blank...')

end
--

I'm assuming that it has to go in some kind of condition. Am I supposed
to run the owners find through some sort of block to validate for each
widget I've found in @widgets?



@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.

@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.

You probably want to add an :order option to whichever one you use to get a consistent output.

-philip
-- 
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