[LRUG] How to do a db backed enum... or what should I be using...
Chris Kimpton
chris at kimptoc.net
Wed Sep 7 01:46:49 PDT 2011
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
More information about the Chat
mailing list