Tim Reistetter
Tim Reistetter

Reputation: 839

Rails one form to edit many records of same model

Let's say I have a users model, a breed model, and then a pets model. A user will have many pets of different breeds. I want a form that looks like this:

[Drop Down Menu to Select Pet Name]

[Name] <--- To edit name if desired

[Breed]

[Age]

[Color]

So if a user has 10 different pets, there would be ten names of pets in the "Drop Down Menu to Select Pet Name". When a user picks a name out of the drop down, the other fields should be prefilled. Hopefully there would be a way to delete a record or add a new one as well.

My instinct is in my view to iterate through the forms, wrap them in divs, and then use JS to control which one is visible. That seems needlessly complicated though. Is that really the best way to do it?

Users probably won't have more than 50 records.


EDITED TO ADD:

Ok, so I think I am getting this a little bit more. This is what I should do. In my controller I should have something like:

current_user.pets.each do
   @pets = pets.find(#ID) 
end

Then in my view I should have:

[Drop down of all pets]

 pets.each do
   <div id=id class=hidden>
   simple_form_for @pet_ID
   </div>
 end

and then a script that fires on the drop down:

<script>
 Hide <div> with previous pet id
  Show <div> with new pet id
</script>

That combined with the nested forms from railscasts should do it, right? Am I making any rookie mistakes here?

Upvotes: 1

Views: 348

Answers (1)

Jarrett Meyer
Jarrett Meyer

Reputation: 19573

Check out the Railscasts from Ryan Bates. Look for nested collections.

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

He provides a very simple solution for nesting collections inside of one-to-many other collections. Ryan is awesome. If you're serious about Rails development, he is totally worth $9/month for his full line of videos.

Upvotes: 1

Related Questions