Forum: Ruby on Rails Assigning default values to attributes in a has_one associat

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
B8873547e864c0f41eb0ccb0f8b18ecf?d=identicon&s=25 Timo Springmann (Guest)
on 2007-05-08 14:51
(Received via mailing list)
Hi List,

I've a little  problem here, for which I can't find a solution:

I have two models, person and event. Event is a polymorphic association
(timeable). In my person model I would like to define an association

class Person < ActiveRecord::Base

    has_one birthday,
        :dependent => :destroy,
        :as => :timeable,
        :class_name => "Event",
        :foreign_key => :timeable_id,
        :conditions => "category = 'birthday'"


As you can see, there's a category field in the event table, which
contain the category of the Event. In this case, is should
contain "birthday".

I would like this category attribute to get set automatically to
whenever I create a new association.

So, calling simething like


in my controller should set the category attribute to "birthday". I was
something like:

    has_one birthday,
        :dependent => :destroy,
        :as => :timeable,
        :class_name => "Event",
        :foreign_key => :timeable_id,
        :conditions => ['category = ?', name.to_s] do
            self.category = "birthday"

But this seems not to work.

Also there are callbacks for collection associations (i.e. before_add
after_add), but this does not work with has_one associations.

So, what would be the best way of doing womthing like this (I sure there
is at
least _one_ way...)

This topic is locked and can not be replied to.