Specifying Inheritance Class Type In Rails Form
I have a parent class called Vehicle, and a couple of children classes: Car开发者_如何学JAVA, Truck, SUV. Im using Single table inheritance and id like in the form to be able to select the TYPE (Car, Truck, SUV), each with a couple of associated fields, and then have rails build the associated type. This sitation is made more complex b/c Vehicles belongs to Fleets, sets of both are updated on the same form.
Is there a way to override the update_attributes and new functions to use the type field and build the child Vehicles as parts of the Fleets?
I don't think it is a good idea to override those, but keep in mind that the only thing that differ between those classes (in the view of the database) is the type field.
So.
car = Car.new params['Car']
car.type = params['Car']['type'] # Here you should check for valid types though
car.save
car.reload # This might work,
# or you have to re-fetch it completely to actually
# change the class of the instance.
Having separate types per form can make it a bit more difficult though, updating them should give the correct type, but otherwise you might have a problem separating the fields (All will have to be of Car, which will collide).
But it is not a problem doing the above for a subclass either.
You can even play it safe by doing Truck.find(params['id']).becomes(Car)
but, if you then have separate logic for Truck, you will loose that.
Update:
In response to the comment:
Yes, this is because type is a protected attribute, which means that you can't assign it through new()
, update_attributes()
, build()
or any other method that allows you to assign values to multiple attributes at once.
If you look in the code I made, I assign it on the second row, that is because of this "error"
精彩评论