Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use becomes in Rails

I have a Post Class and a Comment Class. I have a post object and want to convert it to a Comment object. I went through Rails api and found becomes(klass).For now there is not association between a Post and Comment. So i tried

@post.becomes(Comment)

but becomes method could not be found for @post object. Am i missing something ?

like image 321
Alok Swain Avatar asked Apr 01 '10 04:04

Alok Swain


2 Answers

Put the methods you want both models to use on a module. Then include that module in both models.

like image 113
kikito Avatar answered Oct 13 '22 21:10

kikito


Please note that becomes returns a new object but does not modify the existing object. You need to do the assignment yourself

@post = @post.becomes(Comment)

See the documentation ActiveRecord::Persistence#becomes

like image 29
Maragues Avatar answered Oct 13 '22 19:10

Maragues