I have this model
class Contestcode < ActiveRecord::Base
attr_accessible :code, :used
def self.is_valid(code)
valid = false
contestcode = Contestcode.where('code = ?', code)
Rails.logger.debug("My object: #{contestcode.inspect}");
if (contestcode)
valid = contestcode.used
end
valid
end
end
When I try to run self.is_valid I get this error:
undefined method `used' for #<ActiveRecord::Relation:0x007ff525fde1a8>
The output of the debug statement is:
My object: [#<Contestcode id: 1, code: "aaaaa", used: false, created_at: "2013-01-23 10:21:32", updated_at: "2013-01-23 10:21:32">]
How can I get the used property of contestcode?
Contestcode.wherereturns a collection of Contestcodes. In your case, thecodeyou are searching for is (hopefully!) unique, so it will be a collection of 1 item if it was found or 0 items if it was not.You can see this in your debug statement – notice the square brackets around your object, which indicate that it’s in an array (actually, an
ActiveRecord::Relation, which allows you to chain queries together, but it mostly behaves like an array).What you really want here is
Contestcode.where(...).first, which will extract the Contestcode from the array if it was found, or returnnilif it was not.