How to get a property of an activeRecord object

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?

Answers


Contestcode.where returns a collection of Contestcodes. In your case, the code you 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 return nil if it was not.


Need Your Help

Is it possible to register a top-level intent in the Mirror API?

google-glass google-mirror-api

Example "top-level actions" would be "Google," "take a picture," etc.

Java code for Restricted Boltzmann machines and Deep Learning

java machine-learning neural-network rbm

Since last few days I am reading and studying about Restricted Boltzmann machines and Deep Learning. Now to test the ability of Deep learning I am in search of Java code.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.