sexta-feira, 22 de maio de 2009

Ruby on Rails is becoming quite a piece of software. I've been learning how to work with its latest version to date, 2.3, for a series of workshops on web development. It has surprised me how easy it is now to accomplish a simple task such as multi-model form processing. Let me show what I've been doing lately.

Case study: a school

The example I am going to show my attendees resembles a typical school situation. In a nutsheel:

  • Students have Subjects.
  • Subjects have Students.
  • Students have Grades to Subjects.

rails-relationships-student.png

The Models

Student

class Student < ActiveRecord::Base has_many :grades has_many :subjects, :through => :grades, :uniq => true accepts_nested_attributes_for :grades, :allow_destroy => true end

Subject

class Subject < ActiveRecord::Base validates_uniqueness_of :shortname has_many :grades has_many :students, :through => :grades, :uniq => true end

Grade

class Grade < ActiveRecord::Base belongs_to :subject belongs_to :student validates_presence_of :value end

And the magic trick!

Through accepts_nested_attributes_for, the student's form_for can now accept nested fields through fields_for for setting Grades' data. Everytime a student is created, subjects are not directly associated to him. You need to create a form in which you allow to assign a student the subjects you want.

This tells you that a student can have an array of subject id's. You even get to see what subjects are already assigned and dissociate them just like that! When the associations are done, a new Grade record is created to associate the first two modules. Unfortunately, when the associations are dismantled, the Grade association is gone too. If you know Railscasts, the Complex Forms series explain this task for Rails < 2.3. But now it has become easier and easier to associate models and worrying less about your structure.

terça-feira, 19 de maio de 2009

Rescaldo do Áfricadançar 2009

Para quem não sabe, este Domingo participei na gala final do Africadançar, no Cinema de São Jorge — Lisboa. Em poucas palavras, não valeu tanto a pena: a atribuição dos prémios foi forjada, os concorrentes foram tratados a um nível animalesco e o clima gerado durante o concurso foi caótico; ou seja, parabéns PMPeventos: vocês falharam redondamente. Isto é só um pequeno leque do todo que aconteceu durante e depois da gala. Já lá vão 24 horas e metade já se me olvidou :D