-
Notifications
You must be signed in to change notification settings - Fork 48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Populating associations with empty objects #27
Comments
Hi @otagi, Thanks for the question. Off the top of my head (without testing it first) I think something like this might work: MyController < ApplicationController
def new
@form = LibraryForm.new(:books => Array.new(5) { BookForm.new })
end
end When you instantiate a form object, you can pass in attributes. You just need to set the Thinking about it, you might not need different :books => Array.new(5, BookForm.new) I'd be interested in how that goes. If you have problems, please let me know and I'll write a test case for it 😄 Thanks!! 💖 |
I ended up doing something like this in the controller: def edit
@library = Library.find(params[:id])
[MAX_BOOKS - @library.books.size, 0].max.times { @library.books.build }
@library_form = LibraryForm.from_model(@library)
end because I need to preserve and display the existing books. My next issue is to make Rectify form work with Did you already use nested attributes with Rectify? |
Hi @otagi, Personally, I don't use @form = LibraryForm.from_params(params)
@form.books.each do |book|
library.books.create!(book.attributes)
end So there is more code, but it's easier to understand what is going on and you don't need to juggle the HTML to match the format that Rails needs which always catches me out. How does that sound? Thanks again for the question. |
Thanks for the answer, @andypike. The explicit assignment makes a lot of sense in this context. I like the idea. Less magic, but still easy to read. |
I've looked at all the docs I could find, but still cannot figure out how to do the following. Sorry if I'm missing the obvious.
Let's say we have the following code:
I want to pre-populate the library form with 5 empty book slots by default, so I can fill 5 books at a time in the view.
Is there a way to add new Book objects to the form, before displaying the view?
The text was updated successfully, but these errors were encountered: