Another run at Rails
I’ve started to pick up Rails a few times, always to be interrupted by something–usually either a missing feature that I really needed, or a change in project priorities at work. I finally sat down with it today in an attempt to finish a little project that I’ve been avoiding for months at work.
It was all going well until suddenly one of my classes stopped working right. My Host
class belongs_to
my Group
class. At one point this afternoon, host.group
stopped working from inside of my web app. It worked perfectly with the unit tests, but I got a method undefined exception whenever I tried to access the group
method on a Host
object. Here’s a snippet of the code involved:
class Host < ActiveRecord::Base
belongs_to :group
belongs_to :customer
has_and_belongs_to_many :messages, :order=>"id"
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :packages, :order=>"pkgorder"
has_many :hosts
validates_length_of :name, :maximum=>40
validates_format_of :name, :with => /^[-0-9a-zA-Z.]+$/,
message=>"may only contain letters, numbers, ., and -"
end
These two classes were in their own files, as generated by Rail’s generator script. Can you see what’s wrong? The line right above end
in the Group
definition should start with :message
, not message
. That missing colon in group.rb
broke the Host
class, but only when it was used after Group
was defined. So the unit tests worked, because they tested each class separately, but it failed in a bizarre way when the two were used together.
Things like this make me wonder if maybe Rails isn’t getting just a wee bit too clever for its own good.
Other then that, though, it’s been working great. I’m spending too much time searching the Rails docs for help, but I’m moving right along.