On 13 January 2016 at 07:22, Lei Zhang <
ray.zh...@gmail.com> 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
For that you need A has_and_belongs_many C, or (my preferred solution)
introduce a join model/table and use has_many through. You can't use
has_many as that would require
C belongs_to A
which is not correct.
>
> 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.
>
> Any advice or idea about this requirement ?
I don't understand exactly what your requirement is. in particular
what do you mean by "use C2, C3, C4 as keyword", when each of the Cs
is a record in the db.
If you are trying to get all the As related to records C2, C3 and C4
then that is something like
(
c2.as +
c3.as +
c4.as).uniq
though that may not be the most efficient way.
Colin