How to map 2 db columns to one property
Given a migration
class CreateTalks < ActiveRecord::Migration
def self.up
create_table :talks do |t|
t.integer :duration_hours
t.integer :duration_minutes
end
end
def self.down
drop_table :ta开发者_开发问答lks
end
end
and model
class Talk < ActiveRecord::Base
end
and object
class Duration
attr_accessor :hours, :minutes
end
how do I map the duration_hours and duration_minutes columns to a Duration property in Talk so that I can do
d = Talk.first.duration
hours = d.hours
minutes = d.minutes
I'm aware that in this case I could translate the hours and minutes into seconds and store these in a single column but I'm looking to understand how I could achieve this type of mapping with ActiveRecord.
Write custom accessor methods.
I'm not sure I understand what you're trying to accomplish... especially with storing hours and minutes in two different columns rather than storing a date/time and extracting the hours and minutes .... buuuut... my understanding of attr_accessor is that:
attr_accessor :duration_hours
is equal to:
def duration_hours
@duration_hours
end
def duration_hours=(d)
write_attribute(:duration_hours, d)
end
So what Eimantas is referring to customizing the above methods to store or display information as you see fit... you should already be able to do:
d = Talk.first
hours = d.duration_hours
minutes = d.duration_minutes
Right?
EDIT:
If you're trying to make a list of lectures or something and the amount of time each elapsed using your columns, the way I would do it is (for display purposes only):
def duration
@duration = self.duration_hours.to_s + ":" + self.duration_minutes.to_s
end
Then call using talk.duration. Sloppy but it works.
Look into the composed_of utility in Rails; it allows you to map one or more database columns into instances of Ruby classes.
References:
- http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html
- Section 18.6 of Agile Web Development with Rails Third Edition.
精彩评论