views:

15

answers:

0

Hi all. I'm trying to build a mysql view and am struggling a little. The relationships/tables involved are:

Question
  #fields - subject_id, privacy, keywords
  has_many :taggings
  has_many :tags, :through => :taggings
  has_many :gradings

Tagging (polymorphic join table)
  #fields - taggable_type, taggable_id, tag_id

Tag
  #fields -  name

Grading
  #fields - difficulty_id, age_group_id, question_id

AgeGroup
  #fields - name

Difficulty
  #fields - name

My required view pulls in this data:

questions_id                #simple existing field of questions table
questions_subject_id        #simple existing field of questions table
questions_privacy           #simple existing field of questions table
questions_keywords          #simple existing field of questions table
tag_names                   #concatenated with * on either side of each tag
difficulty_for_age_group_1  #from gradings table
difficulty_for_age_group_2  #from gradings table
..
difficulty_for_age_group_n  #from gradings table

There's two parts to this that are giving me trouble.

1) The simplest (i suspect) is tag_names: for each row in my view i want a list of tags, each of which has a * before and after. So, if question 1 is tagged with tags with names "numbers", "maths", "sets" i want the tags_name field to be numbers*maths*sets.

2) The next bit that's giving me trouble is the difficulty_for_age_group_n fields. I have 8 age groups, with fixed ids, so i can use the id of those age groups in the names. So it's kind of like this, if i was to do it in ruby rather than sql:

AgeGroup.all.each |age_group|
  myview.send("difficulty_for_age_group_#{age_group.id}=", question.gradings.find_by_age_group_id(age_group_id).difficulty_id)
end

if that makes sense. Ie a question has many gradings, up to 1 per age group, and i want the difficulty_id for the grading with age_group_id == x to be difficulty_for_age_group_x.

I'm still a bit shaky on how views actually work: are they regenerated each time i query them? Or are they stored and updated automatically when one of the source tables is updated? If it's the former then i suppose my sql to generate the view needs to be as efficient as possible?

Grateful for any advice - max