我一直在這一天掙扎在最後幾天,一些幫助將不勝感激。名[字符串],信用[布爾],有效[布爾] 在Rails應用程序的一個窗體上創建多個記錄
- 帳戶:有兩種型號一個Rails應用程序
當建立在http://localhost:3000/balances/new
新balance
,形式看起來是這樣的:
我怎樣才能讓用戶可以能夠同時創建多個餘額?日期字段應該只有一個文本框,應該用於創建的所有餘額記錄,但在表單上應該有多個帳戶下拉列表和餘額文本框。
我試過查找嵌套窗體,但我很掙扎。
CODE
模式
create_table "accounts", force: :cascade do |t|
t.string "name"
t.boolean "credit"
t.boolean "active"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "balances", force: :cascade do |t|
t.decimal "balance"
t.date "date"
t.integer "account_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
account.rb
class Account < ActiveRecord::Base
has_many :balances
validates :name, presence: true, length: { maximum: 250 },
uniqueness: { case_sensitive: false }
end
balance.rb
class Balance < ActiveRecord::Base
belongs_to :account
#default_scope -> { order(date: :desc) }
validates :account, presence: true, length: { maximum: 250 }
end
accounts_c ontroller.rb
....
def new
@account = Account.new
end
def create
@account = Account.new(account_params)
respond_to do |format|
if @account.save
format.html { redirect_to accounts_path, notice: 'Account was successfully created.' }
format.json { render :show, status: :created, location: @account }
else
format.html { render :new }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
....
balances_controller.rb
....
def new
@balance = Balance.new
end
def create
@balance = Balance.new(balance_params)
respond_to do |format|
if @balance.save
format.html { redirect_to balances_path, notice: 'Balance was successfully created.' }
format.json { render :show, status: :created, location: @balance }
else
format.html { render :new }
format.json { render json: @balance.errors, status: :unprocessable_entity }
end
end
end
....
餘額/ _form.html.erb
<%= form_for(@balance) do |f| %>
<% if @balance.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@balance.errors.count, "error") %> prohibited this balance from being saved:</h2>
<ul>
<% @balance.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :date %><br>
<%= f.text_field :date %>
</div>
<div class="field">
<%= f.label :account_id %><br>
<%= f.collection_select(:account_id, Account.all.where(active: true).order('name ASC'), :id, :name,{})%>
</div>
<div class="field">
<%= f.label :balance %><br>
<%= f.text_field :balance %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
人們可以在餘額表上創建固定數量的餘額嗎? – jvillian
@jvillian不,理想情況下,一個人應該能夠輸入的餘額數量應該等於活動的賬戶數量(「其中active = true的賬戶數量)」。我已經用模式更新了OP。 – Bhav
做我認爲你想要做的事情將需要一些DOM操作與JavaScript ...除非你想一次創建一堆表格。一個更簡單的解決方案是將該窗體變成一個遠程窗體(使用'remote:true'(如果你只是試圖避免頁面重新加載)。 – wspurgin