Forum: Ruby on Rails Are the find_ methods strictly a SQL thing?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Duane (Guest)
on 2006-06-07 23:54
I've had a number of occasions now where I want to find something in my
model that is not on the primary object.  For instance I've got a class
Alert that has_one Status.  Status has a "label".

I want to find all of my Alert objects and order the results
alphabetically by status label.

Can I do that without going into SQL?  Right now I find myself doing an
Alert.find :all, :joins=>"as a join status s on a.status_id=s.id",
:order=>"label"  (that's from memory, sorry if there's any syntax
errors)...

but there's gotta be a better way?
Brian H. (Guest)
on 2006-06-08 00:20
(Received via mailing list)
This is all possible with associations.

Are you sure Alert has_one status?  This implies that the alerts table
does not have a status_id column.

If it does, then you want belongs_to :status

Now, this is easy if status has a field called label


@alerts = Alert.find :all, :include =>:status, :order => 'label asc'

If Status has a label_id column  (and there is a Label model, and
Status belongs_to :label) then you'll have to do a little more work

And by a little, I mean hardly any


@alerts = Alert.find :all, :include =>[{:status => :label]}, :order =>
'label asc'

This is untested, so if any of this is buggy, let me know and I'll help
fix it.
Duane (Guest)
on 2006-06-08 04:25
Hi Brian,

You are correct, I meant "belongs_to" -- there are a fixed number of
Status objects, each with unique ID, and a variable number of Alert
objects each of which points to one of them.

I see that :include is probably what I should be using in situations
like this.
Knew there had to be something :).

Thanks!

D
Brian H. wrote:
> This is all possible with associations.
>
> Are you sure Alert has_one status?  This implies that the alerts table
> does not have a status_id column.
>
> If it does, then you want belongs_to :status
>
> Now, this is easy if status has a field called label
>
>
> @alerts = Alert.find :all, :include =>:status, :order => 'label asc'
>
> If Status has a label_id column  (and there is a Label model, and
> Status belongs_to :label) then you'll have to do a little more work
>
> And by a little, I mean hardly any
>
>
> @alerts = Alert.find :all, :include =>[{:status => :label]}, :order =>
> 'label asc'
>
> This is untested, so if any of this is buggy, let me know and I'll help
> fix it.
This topic is locked and can not be replied to.