Rails - Create form fields dynamically and save them
- by Frexuz
Im building an ad-system where users can dynamically create 'fields' for each ad type.
My models and example values:
AdType:
| id | name
|----|-----
| 1 | Hotel
| 2 | Apartment
AdOption:
| id | ad_type_id | name
|----|------------|-----
| 1 | 1 | Star rating
| 2 | 1 | Breakfast included?
| 3 | 2 | Number of rooms
AdValue: (Example after saving)
| id | ad_id | ad_option_id | value
|----|-------|---------------|------
| 1 | 1 | 1 (stars) | 5
| 2 | 1 | 2 (breakfast) | true
Ad: (Example after saving)
| id | description | etc....
|----|-----------------|--------
| 1 | very nice hotel | .......
So lets say I want to create a new ad, and I choose Hotel as the ad type.
Then I need my view to dynamically create fields like this: (I'm guessing?)
[Label] Star rating:
[hidden_field :ad_id] [hidden_field :ad_option_id] [text_field :value]
[Label] Breakfast included?
[hidden_field :ad_id] [hidden_field :ad_option_id] [text_field :value]
And also, how to save the values when the ad record is saved
I hope this is understandable. If not just ask and I'll try to clarify.