1

I have an array of strings that are to serve as params for a where call in a model. How do I append each of the strings in the models where call and return the active record relation for an additional limit call

I have tried the following but it only adds the first item to the where clause

array = ['active = true', 'expired = false', 'created_at > 2017-04-18 10:36:28']
array.reduce { | item | Post.where(item) }

returns

Posts.where('active = true')

whereas am begging for

Posts.where('active = true').where('expired = false').where('created_at > 2017-04-18 10:36:28')

Thanks.

1 Answer 1

3

Just join array's elements into a single string:

array.join(' AND ')
#=> "active = true AND expired = false AND created_at > 2017-04-18 10:36:28"

And use it:

Post.where(array.join(' AND '))

P.S.

created_at > 2017-04-18 10:36:28 will probably throw you a syntax error, but that's out of the question's scope.

Sign up to request clarification or add additional context in comments.

2 Comments

You mean AND, not ,, otherwise you need an hash
Good morning bro ^_^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.