搜索数组而不是 where 的正确方法
Correct way to search an Array instead of where
如何用where
查询搜索数组?正确的方法是什么?
你有这样的协会:
# Foo has many bars
Foo.first.bars
控制器:
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
Array 不是 where
,正确的查询词是什么?
您可以使用select 方法在给定特定条件的情况下过滤掉数组中的值。
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
或者对于您的特定示例:
@bars = @datas.map { |d| d.bars }.select { |b| b.name.include? params[:email] }
但是,由于您实际上没有柱形数组并且必须创建它,所以这只是一个不必要的步骤,更直接的解决方案是:
@datas = Foo.where(email: current_user.email)
# @bars is an array
@bars = @datas.map { |d| d.bars.where("name like ?", "%#{params[:email]}%") }
或
# @bars is an ActiveRecord object
@bars = Bar.where(id: @datas.pluck(:id)).where("name like ?", "%#{params[:email]}%")
如何用where
查询搜索数组?正确的方法是什么?
你有这样的协会:
# Foo has many bars
Foo.first.bars
控制器:
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
Array 不是 where
,正确的查询词是什么?
您可以使用select 方法在给定特定条件的情况下过滤掉数组中的值。
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
或者对于您的特定示例:
@bars = @datas.map { |d| d.bars }.select { |b| b.name.include? params[:email] }
但是,由于您实际上没有柱形数组并且必须创建它,所以这只是一个不必要的步骤,更直接的解决方案是:
@datas = Foo.where(email: current_user.email)
# @bars is an array
@bars = @datas.map { |d| d.bars.where("name like ?", "%#{params[:email]}%") }
或
# @bars is an ActiveRecord object
@bars = Bar.where(id: @datas.pluck(:id)).where("name like ?", "%#{params[:email]}%")