views:

58

answers:

2

Given the following hierarchy

class Content < ActiveRecord::Base end
class Page < Content end
class Post < Content end

Is it possible to create for example, Page content (indirectly) using the following style:

c = Content.new c.type = Page c.title = 'test' c.save!

Looks like type is also a ruby method on the object.

A: 

Definitely, but you have to use write_attribute

c.write_attribute(:type, "Page")
c.save
Ben Hughes
wat's the difference between c.type = Page, c.write_attribute(:type, "Page") and c.send(:type=, "Page"). I believe understandingly all these three methods are doing is setting @type = "Page", isn't it? Also is there going to be any problem if I define my own getter and setter methods for type, which overrides the object.type method ?
satynos
on second check, c.type = "Page" is exactly equivalent to c.write_attribute(:type, "Page"). The key thing is that it has to be a string value. As long as your override of type still returns sensible values, you should be fine. You can also change the STI column by changing the value of inheritance_column.
Ben Hughes
A: 

I'd recommend doing something like this...

klass = "Page"
klass.constantize.create(:title=>'title')

If you just monkey around with the 'type' attribute, you won't have any methods you override in the subclass in your object.

_Kevin