Forum: Ruby on Rails how do I use ActiveRecord for selects that return data across multiple tables, or a database view? (

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.
Greg H. (Guest)
on 2009-02-02 01:19
(Received via mailing list)
Hi,

If I want to return SQL data that cuts across multiple models (e.g.
not specific to one mode) how do I do this?  Actually the use case
could be either (a) custom SQL I want to call or via (b) SQL call to a
database view I've created?

The select method
http://api.rubyonrails.org/classes/ActiveRecord/Co...
seems to be what I need however when I try to use this I'm getting an
error:

>> ActiveRecord::Base.connection.select("select * from categories")
NoMethodError: private method `select' called for
#<ActiveRecord::ConnectionAdapters::MysqlAdapter:0x253710c>
        from (irb):11
>>




--
Greg
http://blog.gregnet.org/
James B. (Guest)
on 2009-02-02 01:33
Greg H. wrote:
> Hi,
>
> If I want to return SQL data that cuts across multiple models (e.g.
> not specific to one mode) how do I do this?  Actually the use case
> could be either (a) custom SQL I want to call or via (b) SQL call to a
> database view I've created?

If I understand your question then the way to do this is through
associations defined in your model.  You can have more than one
association defined between identical tables, each with a different name
and select conditions.

See:
http://api.rubyonrails.org/classes/ActiveRecord/As...
Greg H. (Guest)
on 2009-02-02 03:17
(Received via mailing list)
ok - I see I can do the following

   ActiveRecord::Base.connection.select_all('select * from categories')

and get a hash back



2009/2/2 Greg H. <removed_email_address@domain.invalid>:
> error:
> --
> Greg
> http://blog.gregnet.org/
>



--
Greg
http://blog.gregnet.org/
James B. (Guest)
on 2009-02-02 04:53
Greg H. wrote:
> ok - I see I can do the following
>
>    ActiveRecord::Base.connection.select_all('select * from categories')
>
> and get a hash back
>

How is that superior to:

    Category.find(:all)

Or, if you have conditions:

    Category.find(:all, :conditions => [:status = ?, my_status])
This topic is locked and can not be replied to.