Relaciones de ActiveRecord: métodos de consulta adjuntos

Is there a way to conditionally append query methods to a ActiveRecord::Relation?

For instance, I'm searching for Users, but I only was the last_name included in the search under certain conditions. Can you append queries to an ActiveRecord::Relation object?

i_want_to_search_for_last_names = true
pending_relation = User.where(:first_name => "John")
pending_relation << where(:last_name => "Doe") if i_want_to_search_for_last_names
@users = pending_relation.all

preguntado el 08 de noviembre de 11 a las 17:11

1 Respuestas

You code is almost right, except some things. Here what you can do (don't forget: you deals with ActiveRelation):

i_want_to_search_for_last_names = true
@users = User.where(:first_name => "John")
@users = @users.where(:last_name => "Doe") if i_want_to_search_for_last_names

As for me - I used this technique in my projects. Hope it helps you.

respondido 08 nov., 11:21

That works! It's a multi-line User.where(:first_name => "John").where(:last_name => "Doe"). Your approach should have occurred to me :) Thanks for the brain jolt. - dhulihan

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.