问题
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