Forum: Ruby on Rails Activerecord, Join, Select *

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.
338f03da6bc32023d026868eb25afc4d?d=identicon&s=25 David B (Guest)
on 2014-04-14 08:03
(Received via mailing list)
After much searching I have been unable to find the correct information
on
selecting * between a table join.



Here is the query I am dealing with:



Assignment.joins("LEFT JOIN courses ON courses.id =
assignments.context_id
LEFT JOIN enrollments ON enrollments.course_id =
courses.id").includes(:courses).where(:enrollments => {:user_id => '8',
:course_id => '1', :workflow_state => 'active'})



And I would like to select, assignments.* and courses.*, but joins only
selects the table calling the joins, assignments.*



Any help on this issue would be greatly appreciated. I feel like I am
missing something simple
4c6bde00168d595053c09aac7e487f8e?d=identicon&s=25 Colin Law (Guest)
on 2014-04-14 10:11
(Received via mailing list)
On 14 April 2014 01:01, David B <dbroadlick@gmail.com> wrote:
> After much searching I have been unable to find the correct information on
> selecting * between a table join.
>
> Assignment.joins("LEFT JOIN courses ON courses.id = assignments.context_id
> LEFT JOIN enrollments ON enrollments.course_id =
> courses.id").includes(:courses).where(:enrollments => {:user_id => '8',
> :course_id => '1', :workflow_state => 'active'})

Can I ask if there is a good reason that you are doing it this way
rather the Rails way using associations?  If you do not know then tell
us about the models and associations and what you are trying to
achieve with the query.

Colin
00dea966b408b532468c8a472a4ad52b?d=identicon&s=25 Sergey Sein (Guest)
on 2014-04-14 10:45
(Received via mailing list)
You can use select method to define selectable fields like
Assignment.select('assignments.*,  courses.*') but you'll get the array
of Assignment
objects with course columns.

More natural code is
Enrollment.where(user_id: 8, course_id: 1, workflow_state:
'active').preload(courses: [: assignments])

You'll get array of Enrollment with loaded association objects
(Assignment
and Course). It takes 3 simple and fast sql queries.

понедельник, 14 апреля 2014 г., 4:01:43 UTC+4 пользователь David B
написал:
This topic is locked and can not be replied to.