Fixtures add data directly into the database. If you want to pass data to a model instead, consider using factories (Factory Girl is a good library).
You may already have a big investment in fixtures, but factories are well worth a look.
Question
I have a simple Rails 3 model, with an attr_accessor that doesn't have a field in the database, and I need to set it up using fixtures, because of my initialization setup.
But when I try it, I get an error about the unknown column.
Is there another way to do this?
My model:
class Timeslot < ActiveRecord::Base
attr_accessor :interval
after_initialize :init
def init
self.interval ||= 15
self.start_time ||= Time.local(0, 1, 1)
self.end_time = self.start_time.advance :minutes => self.interval
end
end
Solution 2
Fixtures add data directly into the database. If you want to pass data to a model instead, consider using factories (Factory Girl is a good library).
You may already have a big investment in fixtures, but factories are well worth a look.
OTHER TIPS
Fixtures are end state. Meaning, what's in your database is output after you've called attr_accessor. So end_time
would always be calculated for you if you were using it in a test like @timeslot = timeslots(:your_name_of_fixture)
. You don't need to worry about them in the Fixture, except for when you are setting it up.
Now, I've not seen an after_initialize
before, but i see it's a callback function. To me, you are setting an interval in a view. Probably not programmatically (unless it's that default 15 minutes there).
Switching to a before_save
callback (if you want your people to be able to change intervals on edit too) like:
class Timeslot < ActiveRecord::Base
attr_accessor :interval
before_save :set_times
def set_times
self.interval ||= 15
self.start_time ||= Time.local(0, 1, 1)
self.end_time = self.start_time.advance minutes: self.interval
end
end