Filtering out unnecessary fields_for records when creating a transaction

606 Views Asked by At

This question is related to one I asked a couple of months ago: Simple_Fields_For: Multiple Blank Lines on a Form

In that I needed to created a number of blank journal lines on a form with a header in which I then created several records: The journal header, and a number of journal lines. The question was answered and I got it working.

However, I have a follow up question:

I ended up building more blank journal lines than necessary, so that there is plenty of space in the form for users to add lines. However when I perform the create, I end up with several 'blank' entries in the table if not all the lines are filled out.

Is there a Railsy way to filter out these lines so that they are ignored when creating the transaction?

I figure I could pre-process the params, or add lines one at a time checking as I go, but I'd prefer a more Rails suitable method. Is there one?

1

There are 1 best solutions below

1
On

I guess you want to filter out few things from your collection while rendering your fields_for.

fields_for takes in second parameter which contains the elements in the collection. By default the entire collection is passed or you can override by giving a filter condition.

<%= f.fields_for :journal_lines,@journal.journal_lines.present? do |jl| %>

<% end %>

Hope this helps for someone else in future.