Re: [Rails] Select and inner join
On Feb 15, 2013, at 10:12 AM, Colin Law wrote:
> On 15 February 2013 10:05, Lorenz Blackbird <lists@ruby-forum.com> wrote:
>> I have a many-to-many relationship in my course model in this way:
>>
>> has_many :course_paragraphs
>> has_many :paragraphs, :through => :course_paragraphs
>>
>> I use an inner join to select the paragraphs of my course:
>>
>> Paragraph.joins(:course_paragraphs => :course)
>> .where('course_paragraphs.course_id' => @course.id)
>
> You don't need to do that. If you have a course in @course then its
> paragraphs are just @course.paragraphs. It is rare to have to use
> joins when working with Rails if you have got the associations right.
>
>>
>> This works, but I want to select an array containing only the ids of
>> paragraphs.
>
> I think this should work.
> @course.paragraphs.select( :id )
>
> Colin
ActiveRecord actually gives you a method for exactly this:
@course.paragraph_ids
-Rob
>
>>
>> By this solution I get an error:
>>
>> @p_ids = Paragraph.select(:id)
>> .joins(:course_paragraphs => :course)
>> .where('course_paragraphs.course_id' => @course.id)
>>
>> Mysql2::Error: Column 'id' in field list is ambiguous: SELECT id FROM
>> `paragraphs` INNER JOIN `course_paragraphs` ON
>> `course_paragraphs`.`paragraph_id` = `paragraphs`.`id` INNER JOIN
>> `courses` ON `courses`.`id` = `course_paragraphs`.`course_id` WHERE
>> `course_paragraphs`.`course_id` = 1
>>
>> By this solution, the array contain hexadecimal values:
>>
>> @p_ids = Paragraph.select('paragrahs.id')
>> .joins(:course_paragraphs => :course)
>> .where('course_paragraphs.course_id' => @course.id)
>>
>> Where in my problem?
>>
>> Thanks to all.
>>
>> --
>> Posted via http://www.ruby-forum.com/.
>>
>> --
>> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
>> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
>> To post to this group, send email to rubyonrails-talk@googlegroups.com.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home