Rails .reject Turns Type ActiveRecord::Relation into Type Array

大憨熊 提交于 2020-01-02 08:25:56

问题


I want to use the .reject method in Rails to remove the current_user from a search. I do this as follows:

@users = User.where{(firstname =~ my{"%#{params[:term]}%"}) | (lastname =~ my{"%#{params[:term]}%"}) | (email =~ my{"%#{params[:term]}%"})}.select("id,firstname, lastname")
@users = @users.reject{|u| User.find(u.id) == current_user}

After the first line, if I call @users.class, I get ActiveRecord::Relation, but after using the .reject method, if I call @users.class I get Array.

How can I maintain an ActiveRecord::Relation after using the .reject method? I need an ActiveRecord::Relation in order to use the .paginate method in my next line, which is:

@user = @users.paginate(:page => params[:page], :per_page => params[:page_limit])

回答1:


You should use always ActiveRecord api query methods to get an ActiveRecord::Relation (reject isn't). For example, combine where:

@users = User.where(your_first_conditions).
              where("id != :id", id: current_user.id).
              select([:id, :firstname, :lastname])


来源:https://stackoverflow.com/questions/22029598/rails-reject-turns-type-activerecordrelation-into-type-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!