Ruby Rails: has_many, auto-report column

Considering 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 am trying to do is set the column affects_class

to automatically '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 need to install modifier.affects_class

. After all, I don't need to install modifier.affects_id

; which are automatically set by the relationship has_many

. Is there some option that I can set to has_many

? Or am I stuck to install it every time?

+2


a source to share


1 answer


Forgive me if what I say does not make any sense ... but I cannot verify what I am going to propose, so ...

railsapi.doc

says the following about the option :conditions

in relation to has_many

:

[...] Make entries from the association is limited if the hash is in use. has_many: posts,: conditions => {: published => true} will create published posts from @ blog.posts.create or @ Blog.posts.build.

So, if you set the condition using the hash

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

      



and create 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 sure about using it self.name

. I don't know if this is the correct class name.

Anyway, let me know if it works. This is new to me and very useful.

+4


a source







All Articles