我是 Rails 新手,我看到经常有人问这个问题,但我仍然遇到一些问题。谁能告诉我哪里做错了。
[中心 Controller ]
class CentersController < ApplicationController
def index
@centers=Center.all
end
def new
@center=Center.new
end
def create
@center=Center.new(para)
if @center.save
flash[:notice] = "success man."
redirect_to @center
else
render 'new'
end
end
private
def para
params.require(:center).permit(:registration_number,:registration_date,
:tin_number,:no_of_trainers,:total_numbers,:name,:address,
:contact_no,:registration_fee,:monthly_fee,:status,:sector_id)
end
end
[中心/index.html.erb]
<%=form_for :centers_index_path do |f| %>
<fieldset>
<legend>Centers</legend>
<div>
<%= f.text_field :registration_number, :placeholder=>"Enter registration number" %>
</div>
<div>
<%= f.text_field :registration_date, :placeholder=>"Enter registration date" %>
</div>
<%= f.submit :submit %>
</fieldset>
<% end %>
<br>
[中心.rb]
class Center < ActiveRecord::Base
validates :registration_number,presence: true
validates :registration_date
end
[移民]
class CreateCenters < ActiveRecord::Migration
def up
create_table :centers do |t|
t.integer :registration_number
t.date :registration_date
t.integer :tin_number
t.integer :no_of_trainers
t.integer :total_numbers
t.string :name
t.string :address
t.string :contact_no
t.integer :registration_fee
t.integer :monthly_fee
t.integer :status
t.integer :sector_id
t.timestamps
end
add_foreign_key :centers,:sectors
end
在控制台上出现此错误
Started POST "/centers" for 127.0.0.1 at 2016-01-20 15:00:47 +0530
Processing by CentersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"11rrttKOGdWrCClqnB/aTuHWLT4UsoQRWkpiwwk6bBxgSBO85f532LytX3d6rJml8cW3lMjnvB6eUpAeTHBA6A==", "centers_index_path"=>{"text"=>"", "password"=>"[FILTERED]"}, "commit"=>"submit"}
Completed 400 Bad Request in 2ms (ActiveRecord: 0.0ms)
最佳答案
您应该在form_for
中使用@center
!
<%=form_for @center do |f| %>
这会将表单绑定(bind)到您的模型,并且参数实际上会到达它们需要的地方!
在new
操作(GET)上,它将创建一个新的空center
,在create
操作(POST)上,它将填充center
带有表单的数据!
这应该有效!
更新:
您没有使用 new 操作,您应该将表单作为名为 new.html.erb
的文件中的一部分,然后调用 new。
我建议您生成一个新的脚手架来查看 REST 设置的外观并从那里获取它。你可以这样做:
rails g scaffold my_center registration_number:integer registration_date:date tin_number:integer ... ...
然后:
rake db:migrate
这将为您提供 my_center 的工作示例,并且非常容易调整!
关于ruby-on-rails - 参数缺失或值为空 : center,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896570/