Sylar Sylar - 11 days ago 5
Ruby Question

Correct way to search an Array instead of where

How to query search an Array with

where
? What's the correct way?

U have an association like this:

# Foo has many bars
Foo.first.bars


Controller:

def index
@bars = []
@datas = Foo.where(email: current_user.email)
@datas.map { |d| @bars.push(d.bar).where("name like ?", "%#{params[:email]}%") }

respond_to do |format|
format.html
format.json { render json: @bars }
end
end


Instead of
where
for Array, what is the correct query term?

Answer

You can use the select method to filter out values in an array given a certain condition.

[1,2,3,4,5].select { |num| num.even? }   #=> [2, 4]

Or for your particular example:

@bars = @datas.map { |d| d.bars }.select { |b| b.name.include? params[:email] }

However, since you actually don't have an array of bars and would have to create it, this is simply an unnecessary step and a more straightforward solution would be:

@datas = Foo.where(email: current_user.email)
# @bars is an array
@bars = @datas.map { |d| d.bars.where("name like ?", "%#{params[:email]}%") }

or

# @bars is an ActiveRecord object
@bars = Bar.where(id: @datas.pluck(:id)).where("name like ?", "%#{params[:email]}%")