好的,到目前为止我有这个搜索查询:
if Object.const_get(params[:model]).find(params[:id]) == @current_department
sent = Message.where(sender_username: params[:username], recipient_username: params[:username])
recieved = Message.where(recipient_username: params[:username])
end
现在我想稍微更改一下recieved
-搜索查询:
recieved = Message.where(recipient_username: params[:username])
类似于:
Message.where(sender_username: @current_department.employees.each { |f| f.username}, recipient_username: params[:username]}
但不知何故我无法将多个用户名传递给搜索:
sender_username: @current_department.employees.each { |f| f.username}
我没有收到错误,但我的搜索查询仍然无法正常工作!我该如何更改我的查询?谢谢
最佳答案
你必须使用 .map
而不是 each,map 返回 block 中返回值的数组,each 只迭代数组的每个元素:
sender_username: @current_department.employees.map{ |f| f.username }
速记(如果 ruby <= 1.8.7 不要使用它):
sender_username: @current_department.employees.map(&:username)
还有一点改进,使用 pluck(这是一个 SQL 选择):
sender_username: @current_department.employees.pluck(:username)
pluck(:username)
将只选择表的用户名列并将其转换为 Ruby 对象。而 map(&:username)
将加载 ruby 记录中的每条记录,然后仅选择用户名属性。
关于ruby-on-rails - 搜索查询传递几个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19817893/