views:

66

answers:

2

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 ?

A: 

I'm assuming you are talking about classes deriving from ActiveRecord::Base. In that case, I think you have two options if you really want to convert posts into comments (which seems a bit strange to me):

  • You can have just one class (e.g. Entry) with an attribute which marks it as a post or a comment, which you would set as appropriate
  • You could create and save a new comment object containing the text of the post object, and then delete the post object.
Alex - Aotea Studios
I am trying to typecast objects. I defined a method for some class and some other class object also needed to access that method. I could also include it in a common helper, but i came across this and this dint work out as i thought. So wanted to know how it works.
alokswain
Ok, in that case I think that for `becomes` to work Post has to inherit from Comment. As the documentation says, `becomes` is useful when you want an instance of a subclass to appear as an instance of a superclass.
Alex - Aotea Studios
A: 

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

egarcia