I’m getting the following error in my rails app:
comparison of User with User failed
The relevant section of my controller looks like this:
class AssessmentsController < ApplicationController
before_filter :authenticate_user!
respond_to :html, :xml, :js, :pdf
def index
@user = current_user
@account = Account.find(@user.account_id)
@assessments = Assessment.all
respond_with @assessments
end
The relevant section of my view looks like this:
<%= form_for(@account) do |a| %>
<%= a.fields_for :users, @account.users.build do |u| %>
....
<%= a.submit "Sign-up", :class => "button", :disable_with => "Saving..." %>
<% end %>
<h1>Current users</h1>
<% for @user in @account.users.sort! { |b,a| a.id <=> b.id } %>
<%= render :partial => 'user' %>
<% end %>
The error seems to be originating around the for @user in @account.users.sort! section according to the error model, but removing it seems to be the addition of the @account.users.build in the fields_for section that creates it (but I need this as I want the user to be able to create a new user for that account. Can someone enlighten me to what is generating this?
The error is indeed occurring on that line, because ActiveRecord models don’t implement comparables by default. So when you say
@account.users.sort!, the sort bombs out since it has no way to compare users with users.There’s two things you can do here:
Implement the comparison operator for your user model. Check out this link for a blog post on how to do it, but it’d be something like:
Tell the sort directly what comparison to use, like this: