i have implemented testapp model "author" has-many "books" following http://railscasts.com/episodes/196-nested-model-form-revised. using 1 simple relation in example, nothing else.
the app works perfectly, can add , delete books dynamically author using "link_to_add_fields" etc. save, modify, delete works should.
the form looks this:
<%= simple_form_for(@author) |author_form| %> <%= author_form.input :name %><br /> <%= author_form.input :born %><br /> <h1>books author</h1> <!-- assume @author.books (somehow...) --> <%= author_form.simple_fields_for :books |book_fields| %> <%= render partial: "book_fields", locals: {f: book_fields} %> <% end %> <%= link_to_add_fields "add book", author_form, :books %> <%= author_form.submit %> <% end %>
i have partial "_book_fields.html.erb" used both edit view , js-code.
<fieldset class="book"> <%= f.input :title %><br /> <%= f.input :pages %><br /> <%= f.hidden_field :_destroy %> <%= link_to "remove", '#', class: "remove_fields" %> </fieldset>
i have cover field upload picture using paperclip removed brevity.
the problem have want create "add single book author"-action/view. can't wrap head around how partial should used.
lets have author-action looks author-id, , creates empty book (using @author.books.build
?) how show such form in view action possible add book author.books array? can use existing partial?
lets want separate action/view remove book author, how work?
to have expressive , dryed code i:
first, rename partial reused, choose name difficult.
second, let's have 2 actions in authorscontroller
: new_one
, new_many
. names difficult here. then, have app/views/authors/new_one.html.erb
, app/views/authors/new_many.html.erb
third, call renamed partial this:
# new_one = render partial: 'renamed_partial', locals: { link_to_add: false } # new_many = render partial: 'renamed_partial', locals: { link_to_add: true }
and renamed partial change:
<%= simple_form_for(@author) |author_form| %> <%= author_form.input :name %><br /> <%= author_form.input :born %><br /> <h1>books author</h1> <!-- assume @author.books (somehow...) --> <%= author_form.simple_fields_for :books |book_fields| %> <%= render partial: "book_fields", locals: {f: book_fields} %> <% end %> <%#### here change! ####%> <%= link_to_add_fields "add book", author_form, :books if link_to_add %> <%= author_form.submit %> <% end %>
i forgot, right, should use @author.books.build
add new book.
Comments
Post a Comment