I have a form for one model with a couple of input boxes and one dropdown box where type ( TypeA
and TypeB
) of the model can be picked. Let's say models are something like this:
// car has columns name and country
class Car < ActiveRecord::Base
end
// has columns a_property_1 and a_property2
class TypeAProperties < ActiveRecord::Base
belongs_to :cars
end
// has columns b_property_1 and b_property2
class TypeBProperties < ActiveRecord::Base
belongs_to :cars
end
After user opens form, by default there should be displayed fields for name, country, dropdown box with TypeA
selected, a_property_1 and a_property2.
If user navigates to dropdown box and selects TypeB
, a_property_1 and a_property2 should disappear from screen, and b_property_1 and b_property2 should appear on screen. So, TypeAProperties and TypeBProperties are created depending on selected value from drop down box. Car can have only one property, A or B.
Any ideas how to handle this situation? I am a little bit stuck with this. Thank you.
I believe you should do vise versa, so:
class Cars < ActiveRecord::Base
belongs_to :car_type, polymorphic: true
end
and in type classes
class TypeAPropertySet < ActiveRecord::Base
has_one :car, as: :car_type # or has_many
end
class TypeBPropertySet < ActiveRecord::Base
has_one :car, as: :car_type # or has_many
end
Please refer to the document on the rails polymorphism. So then you be able to use Car
s properties, along with the car_type
in the form.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.