Ruby on Rails 3: Associating extra data with a model
Pretty much a total beginner to Ruby/Rails.
I have a Video with many Sections:
@video = Video.find(params[:id])
@sections=@video.sections;
I want to associate a colour attribute with each Section, but the colour is calculated in the controller, rather than stored in the database.
So far I have been simply creating a @colours
array in my controller where the index matched up with the index of the section
hues = [41, 6, 189, 117, 279]
saturation = 100;
brightness = 45;
@colours = [];
@sections.each { @colours.push Color::HSL.new(hues[j%hues.length], saturation, brightness) }
so that @sections[i]
corresponds to @colours[i]
.
This works fine, but doesn't seem like the best approach. I would like to extend my Sections model so that it has a 'colour' attribute, so that I could access it by doing @sections[i].colour
I tried putting this in models/sectiondata.rb :
class SectionData
extend Section
attr_accessor :colour
end
but wh开发者_开发百科en I try to do SectionData.new
in my Controller I get an error saying it can't find the class. I also don't know how I would get the original @section
to be part of the new SectionData class.
What is the best way to approach this problem? Any tips on my coding style would also be appreciated, Ruby is a big step away from what I'm used to.
I think its a better idea to implement hashes in this situation instead of having two arrays corresponding to each other. For example,
result_hash = {sports_section => 'blue'}
First I tried putting them as attr_accessors in the Section
model, don't do that. Bad coder! They will not show up if ActiveRecord queries the database again for that page load, even if the query is cached. If you need the ActiveRecord methods you can use ActiveModel
Instead, I created a class for the attribute accessors:
sectiondata.rb:
class SectionData
attr_accessor :left, :width, :timeOffset, :colour, :borderColour
end
Then you can work with them using an object which maps a Section object to SectionData:
xxx_controller.rb
@video = Video.find(params[:id])
@sections=@video.sections
require 'sectiondata.rb'
@sectionDatas=Hash.new
@sections.each do |i|
sd=SectionData.new
# set whatever attributes here, e.g.
sd.left= total/multiplier
@sectionDatas[i]=sd
end
Then, given a Section object called 'section', you could access it using @sectionDatas[section]
, and this will work for any database queries that occur in the page of
精彩评论