问题
I am trying to get a number of blank lines on a simple form using simple_fields_for but only one line/record displays. This is the code below, the models, controller, and view.
class Journal < ActiveRecord::Base
has_many :journal_lines
end
class JournalLine < ActiveRecord::Base
belongs_to :journal
end
class JournalController < ApplicationController
def new
@organisation = Organisation.find(params[:organisation_id])
@journal = Journal.new
@journal.journal_lines = Array.new(5, JournalLine.new)
end
...
<%= simple_form_for @journal, :url => {:controller => 'journal', :action => 'create', :id => @organisation.id}, :method => :post do |f| %>
<%= f.input :transaction_date, as: :string, input_html: {class: 'datepicker'} %>
<%= f.input :reference %>
<%= f.input :memo %>
<table>
<tr><td>Account</td><td>Debit</td><td>Credit</td><td>Memo</td></tr>
<%= f.simple_fields_for :journal_lines do |jl| %>
<tr>
<td><%= jl.input :finacct_id, :collection => Finacct.all, :label_method => :full_account_name, :value_method => :id, :label => false ,:include_blank => false %></td>
<td><%= jl.input :debit, :label => false %></td>
<td><%= jl.input :credit, :label => false %></td>
<td><%= jl.input :memo, :label => false %></td>
</tr>
<% end %>
</table>
<%= submit_tag 'Create' %>
<% end %>
I'm not sure why I cannot see more than one journal line on the screen. When I log the journal_lines object I see 5 empty objects, but only one displays in the form.
回答1:
Okay. I did get an answer but it didn't work as answered so the poster deleted it. However, after a lot of messing around it turned out to be the journal model needed the following
accepts_nested_attributes_for :journal_lines
Once I added that, all five blank lines showed up on the form.
The other answer also suggested that I do this in the controller
@journal = Journal.new
5.times do |i|
@journal.journal_lines.build
end
Not sure if that made a difference, but it's in now. Hope this helps.
来源:https://stackoverflow.com/questions/25986384/simple-fields-for-multiple-blank-lines-on-a-form