0

I have a question about STI in rails that I cannot seem to get my head around.

I have 2 models, order.rb

class Order < ActiveRecord::Base
    has_many :answers
end

and answer.rb

class Answer < ActiveRecord::Base
    belongs_to :order
    attr_accessible :value, :input_id, :type
end

answer.rb also has a couple of STI classes like select.rb

class Select < Answer
    validates presence: true
end

The reason for this is that I want to be able to make custom validations and caluclations on different types of answers.

Everything works ok until I'm trying to make a fields_for on answers that is associated to each order. I am abled to instiate each STI class when rendering the form. All of the answers will however end up in the array answers_attributes when the form is submitted and will all be considered as class Answer instead of for example class Select.

Anyone got some idea on how I might solve this issue?

Thanks!

nbon
  • 2,735
  • 2
  • 16
  • 15

1 Answers1

0

I'm not sure if I get your problem right, but maybe you are looking for becomes?

Answer.last.becomes(Select)
fotanus
  • 19,618
  • 13
  • 77
  • 111
  • Hmm, the problem is that some of the STI classes has dynamic attributes through attr_accessor that are rendered in the form and then parsed into value in the STI model. So I think I need them to be in their STI class when posting the form. – nbon Apr 13 '13 at 06:28
  • You might want to check [This post](http://stackoverflow.com/questions/555668/single-table-inheritance-and-where-to-use-it-in-rails) – fotanus Apr 13 '13 at 21:22