views:

35

answers:

1

Given the following Ruby-on-Rails code (1.8.6, 2.3.5):

class MyClass < ActiveRecord::Base
  has_many :modifiers,
    :conditions => ["affects_class = ?", self.name],
    :foreign_key => :affects_id
end

What I'm trying to do is to automatically set the affects_class column to 'MyClass'. In other words:

myInstance = MyClass.find(:first)
modifier = Modifier.new
modifier.affects_class = self.name # Don't want to have to do this
myInstance.modifiers << modifier

I don't want to have to set modifier.affects_class. After all, I don't have to set modifier.affects_id; that's set automatically by the has_many relation. Is there some option I can set on has_many? Or am I stuck having to set it each time?

+2  A: 

Forgive me if what I'll say doesn't make any sense... but I can't test here what I'm about to suggest, so...

railsapi.doc says the following about the :conditions option on a has_many relation:

[...] Record creations from the association are scoped if a hash is used. has_many :posts, :conditions => {:published => true} will create published posts with @blog.posts.create or @blog.posts.build.

So, if you set up the condition using a hash

class MyClass < ActiveRecord::Base
   has_many :modifiers,
      :conditions => {:affects_class => self.name},
      :foreign_key => :affects_id
end

and create the modifiers using

myInstance = MyClass.find(:first)
myInstance.modifiers.create #or myInstance.modifiers.build

won't you get modifiers with the name already set?

I'm just not very confident about using self.name. I don't know if this is the right way to get the class' name.

Anyway, let me know if it works. It's new to me and very useful.

j.
Thank you very much! This did indeed exactly solve my problem! Kudos to you. Switching from an array to a hash, which was a good idea anyway, and then using myInstance.modifiers.create (or build) did exactly what I was looking for.
ChrisInEdmonton
self.name does work for me, but I admit that I'm using it because I'm doing metaprogramming magic to do a variation on discrete event simulation. :)
ChrisInEdmonton
Nice! :) I wasn't very sure about it... glad it helped!
j.