我的问题与此问题类似:Ruby on Rails - Data not saved. Index showing blank values
然而,强大的params匹配答案,似乎没有数据通过。
如果我使用params.require(:banktransaction).permit(...)我收到一个错误: param丢失或值为空
如果我删除了require部分,则添加一行但没有值。
我查看了视图和控制器并检查了我的拼写,对于我的生活,我无法看到我错过的,有人能指出我正确的方向吗?
控制器:
class BankAccountsController < ApplicationController
def delete
end
def destroy
end
def edit
end
def update
end
def index
@bankaccount = BankAccount.all
end
def show
end
def new
@banktransaction = BankAccount.new(:transactionDate => Time.now, :description => params[:description], :credit => params[:credit], :debit => params[:debit])
end
def create
@banktransaction = BankAccount.new(bank_account_params)
if @banktransaction.save
flash[:notice] = "transaction added successfully."
redirect_to(bank_accounts_path)
else
render('new')
end
end
private
def bank_account_params
params.require(:banktransaction).permit(:transactionDate,:description,:credit,:debit)
end
end
查看:
<h1>BankAccounts#new</h1>
<p>Find me in app/views/bank_accounts/new.html.erb</p>
<div class="new transaction">
<h2>Create Transaction</h2>
<%= form_for(@banktransaction, :html => {:multipart =>true }) do |f| %>
<%= render(:partial =>'form', :locals=> {:f => f}) %>
<div class="form-buttons">
<%= f.submit("Create Transaction") %>
</div>
<% end %>
</div>
表格部分:
<%= f.label(:transactionDate) %>: <%= f.date_field(:transactionDate) %><br>
<%= f.label(:description) %>: <%= f.text_field(:description) %><br>
<%= f.label(:credit) %>: <%= f.number_field(:credit) %><br>
<%= f.label(:debit) %>: <%= f.number_field(:debit) %><br>
路线:
Rails.application.routes.draw do
resources :bank_accounts do
member do
get :delete
end
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
答案 0 :(得分:1)
简而言之,你只允许错误的params键。它是bank_account
,您的bank_account_params
应该是
def bank_account_params
params.require(:bank_account).permit(:transactionDate,:description,:credit,:debit)
end
Rails的表单构建器将根据模型名称而不是变量名来构建params。
您的new
操作指定了BankAccount
个实例
def new
@banktransaction = BankAccount.new(:transactionDate => Time.now, :description => params[:description], :credit => params[:credit], :debit => params[:debit])
end
因此表单构建器将使用bank_account
作为参数键而不是变量名banktransaction