STI convert object to other object

17 views
Skip to first unread message

Linus Pettersson

unread,
May 13, 2013, 4:19:08 AM5/13/13
to rubyonra...@googlegroups.com
Hi

I'm using STI and want to convert one object to the other. The reason to why I'm using STI is that I have a report and a full report. First someone reports something and can only enter a few fields. Then and admin can convert this into a full report and fill out the full report. Using STI makes it easier to handle the views, validations etc.

When converting it I just go to the edit action of a full_report, fetch the report and converts it into a full report using the #becomes(FullReport) method. The issue is when I submit this form and I want to save it in the update action I do this:
@report = Report.find(params[:id])
@report = @report.becomes(FullReport) if @report.type.nil?

if @report.update_attributes(report_params) ....
....

The thing is that it doesn't save the type as FullReport when I do this.

Why is that? I can't convert it, save it, reload and update it since the validations will fail.

So, how can I convert the object and update its attributes at the same time?

Linus Pettersson

unread,
May 13, 2013, 10:43:55 AM5/13/13
to rubyonra...@googlegroups.com
Ok, the solution was to not use #becomes and instead just set the type field explicitly before saving.

//Linus
Reply all
Reply to author
Forward
0 new messages