我努力保存信息,但似乎很难。
这是我的控制器 /app/controllers/finance_management/voucher_controller.rb
class FinanceManagement::VoucherController < ActionController::Base
def new
@voucher = Voucher.new
end
def create
Voucher.create(params[:voucher])
end
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
end
这是我的模型 /app/models/voucher.rb
class Voucher < ActiveRecord::Base
end
以下是我的观点 /app/finance_management/voucher/new.html.erb
<%= form_for :obj_voucher, :url => { :controller => "finance_management/voucher", :action => "create" } do |f| %>
Number<%= f.text_field :voucher_num %>
<%= f.submit :submit %>
<% end %>
这是我的routes.rb
Rails.application.routes.draw do
namespace :finance_management do
resources :voucher
end
match ':controller(/:action(/:id(.:format)))', via: [:get, :post]
end
这是我的日志
Started POST "/finance_management/voucher" for 127.0.0.1 at 2016-01-17 21:00:39 -0500
Processing by FinanceManagement::VoucherController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"222222=", "voucher"=>{"voucher_num"=>"1111"}, "commit"=>"submit"}
(0.1ms) BEGIN
SQL (1.5ms) INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
(0.2ms) ROLLBACK
Completed 500 Internal Server Error in 5ms (ActiveRecord: 1.8ms)
ActiveRecord::StatementInvalid (Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')):
我尝试了几种方法,但无法保存信息但却出错:
<%= form_for :user, :url => {:controller=>"finance_management/voucher",:action=>'create'} do |f|%>
<%= form_for @user, :url => {:controller=>"finance_management/voucher",:action=>'create'} do |f|%>
也改变了这个:
def create
@voucher= Voucher.create(params[:voucher_params])
end
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
该字段未保存
Mysql2::Error: Field 'voucher_num' doesn't have a default value: INSERT INTO `vouchers` (`created_at`, `updated_at`) VALUES ('2016-01-18 02:00:39', '2016-01-18 02:00:39')
答案 0 :(得分:1)
ActionController参数不能直接在ActiveModel质量分配中使用,您必须使用strong parameters代替。
答案 1 :(得分:1)
尝试:
def create
Voucher.create(voucher_params)
end
答案 2 :(得分:0)
为了怀疑,以下是代码的结构:
#config/routes.rb
namespace :finance_management do
resources :vouchers
end
#app/controllers/financial_management/vouchers_controller.rb
class FinanceManagement::VouchersController < ActionController::Base
def new
@voucher = Voucher.new
end
def create
@voucher = Voucher.new voucher_params
@voucher.save
end
private
def voucher_params
params.require(:voucher).permit(:voucher_num)
end
end
#app/views/finance_management/vouchers/new.html.erb
<%= form_for [:financial_management, @voucher] do |f| %>
<%= f.text_field :voucher_num, placeholder: "Number" %>
<%= f.submit %>
<% end %>