[LRUG] How to do a db backed enum... or what should I be using...

Riccardo Tacconi rtacconi at gmail.com
Wed Sep 7 01:57:51 PDT 2011


Hi,

I use a gem file.

In your gemfile add:

gem 'enumerated_attribute'

In your model:

enum_attr :doc_type, %w(diploma teacher_reference student_reference
course_outline)

Otherwise you can use (in your model) something like this:

  ROLES = %w[admin manager user].freeze

  def role_in_list
    errors.add(:base, "Role #{self.role} is not allowed") unless
User::ROLES.include?(self.role)
  end

On 7 September 2011 10:46, Chris Kimpton <chris at kimptoc.net> wrote:

> Hi,
>
> Could I pick your brains a little...
>
> I have some status values that I want to store in the DB, but also be
> available in an enum-like way (perhaps that is my mistake...)
>
> My current code is like this:
>
> class Category < ActiveRecord::Base
>
>  has_many :widgets
>
>  def self.CAT1
>    find_by_cat_name("cat1")
>  end
>
> end
>
> This seems to work fine on its own, and when used via the console.
>
> I'd like to use it in a "scope" to restrict a widget query, like so:
>
>
> class Widget < ActiveRecord::Base
>
>  belongs_to :category
>
>  scope :one, where(:category_id => Category.CAT1).order(:created_at)
>
> end
>
> Again, this works fine in the console, I can add widgets to the category
> and the scope picks up the new values.
>
> But when I try the same via my tests, it is not finding the newly created
> widgets.  From the logs, it seems the Category id is not set - as if the
> scope is using an uninitialised version of the Category object.
>
>  test "scope" do
>    assert_equal 0, Widget.all.count
>    assert_equal 0, Widget.one.count
>    assert_equal 0, Widget.two.count
>    assert_not_nil Category.CAT1
>    assert_not_nil Category.CAT2
>    Widget.create(:name => "foo", :size => 2, :category => Category.CAT2)
>    assert_equal 1, Widget.all.count
>    assert_equal 0, Widget.one.count
>    assert_equal 1, Widget.two.count  # this assert fails - gets a 0.
>
>  end
>
> Perhaps I am doing something wrong...
>
> The full (test) project is here -
> https://github.com/kimptoc/scope-enum-tester - using Rails 3.1 (not tried
> 3.0 to see if that could be the issue...)
>
> Thanks,
> Chris
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>



-- 
Riccardo Tacconi
Ruby on Rails and PHP development - System Administration
VIRTUELOGIC LIMITED

http://github.com/rtacconi
http://riccardotacconi.blogspot.com
http://twitter.com/rtacconi
http://www.linkedin.com/in/riccardotacconi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20110907/93cadb0b/attachment-0003.html>


More information about the Chat mailing list