Thank you, I'll check this out.

On Thursday, January 14, 2016 at 1:13:36 AM UTC+8, Jim wrote:
>
> On Wednesday, January 13, 2016 at 2:22:51 AM UTC-5, Lei Zhang wrote:
>>
>> I am going to implement a small and simple search feature in my project. 
>> But got a question about the scenario I have right now. So hope to get some 
>> tips from here.
>>
>> First of all, this is a rails app.
>>
>> There are two models, A and C.
>>
>> A has_many C.
>>
>> That's to say, it might have some situation like this:
>>
>> A1 related to C1, C2, C3, C4
>> A2 related to C2, C3, C4, C5
>> A3 related to C2, C3, C4, C8
>> A4 related to C3, C4, C8, C9
>> A5 related to C4, C8, C9, C20
>>
>> Use C2, C3, C4 as keyword, I can get A1, A2, A3
>> Use C4, C8, C9 as keyword, I can get A4, A5
>>
>> I consider that this can be done by using something straightforward like 
>> A.Cs.includes?(C2,C3,C4). 
>>
>> But that requires an iteration of A. And I concern that it would have 
>> some performance issue.
>>
>
> If you want to load matching As without instantiating the Cs, you could do 
> something like:
>
> A.where(id: C.where(code: params[:codes]).pluck(:a_id))
>
> If you are going to instantiate all As and Cs found anyway, you could just 
> use eager loading:
>
> found_c = C.where(code: params[:codes]).includes(:a)
> found_a = found_c.collect(&:a).uniq
>
> Jim
>

-- 
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 [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/1f6af06e-99eb-4dd8-9127-bd435f8c230d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to