Nick Barrett
Nick Barrett

Reputation: 1051

Turning an ActiveRecord::Relation into a model

very beginner question. I am using Rails 3's query interface as shown:

class User < ActiveRecord::Base

def self.authenticate
 if Rails.env = 'development'
   self.where('username = ?', 'development_user')
 else
   self.where('username = ?', request.env['REMOTE_USER'])
 end
end

end

This is returning an ActiveRecord::Relation object, where in reality I want the User object that relates to the query. How do I turn this into a User object?

Upvotes: 8

Views: 2490

Answers (1)

Chris Heald
Chris Heald

Reputation: 62648

You need to "commit" the query with all, first, or find.

def self.authenticate
 user = Rails.env.development? ? "development_user" : request.env['REMOTE_USER']
 self.where('username = ?', user).first
end

Upvotes: 13

Related Questions