Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and compare :symbols in an ActiveRecord (Ruby on Rails)

Tags:

I thought it would be good to populate a status field in an activeRecord table using constants. However, when it comes to checking if this status has a particular status, I'm having trouble.

If I do the following,

e = Mytable.new e.status = :cancelled e.save 

then refind the record and try and compare my status to the symbol, the check fails. I have some output from the console to show this.

irb(main):060:0> e.status.eql?("cancelled") => true irb(main):061:0> e.status.eql?(:cancelled) => false irb(main):062:0> e.status == :cancelled => false irb(main):063:0> e.status == "cancelled" => true irb(main):064:0> e.status == :cancelled.to_s => true 

Is there a better way of holding a status in a record? Is there a way of testing if a current field value is equal to the :symbol without converting the :symbol to a string? I'm thinking there may be an operator I'm not aware of.

like image 599
seanyboy Avatar asked Jan 27 '12 17:01

seanyboy


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Store_accessor?

The reason is that store_accessor is basically just a shortcut which defines getter and setter methods: # here is a part of store_accessor method code, you can take a look at # full implementation at # http://apidock.com/rails/ActiveRecord/Store/ClassMethods/store_accessor _store_accessors_module.module_eval do keys. ...

Can you use ActiveRecord without rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.


1 Answers

With Rails 4.1.0, you'd probably want to use Active Record enums.

To quote the official release notes:

class Conversation < ActiveRecord::Base   enum status: [ :active, :archived ] end   conversation.archived! conversation.active? # => false conversation.status  # => "archived"   Conversation.archived # => Relation for all archived Conversations   Conversation.statuses # => { "active" => 0, "archived" => 1 } 
like image 84
jiehanzheng Avatar answered Nov 29 '22 08:11

jiehanzheng