jef*_*ale 3 ruby ruby-on-rails strong-parameters ruby-on-rails-4
我查看了几个教程,ruby指南和几个stackoverflow问题.我首先尝试使用simple_form,现在是老式的方式,无法弄清楚为什么params没有通过.
控制器:
def new
@topgem = Topgem.new
end
def create
@topgem = Topgem.new(topgem_params)
if @topgem.save
redirect_to @topgem
else
render 'new'
end
Run Code Online (Sandbox Code Playgroud)
...
private
def topgem_params
params.require(:name).permit(:url, :description, :downloads, :last_updated)
end
Run Code Online (Sandbox Code Playgroud)
模型:
class Topgem < ActiveRecord::Base
has_many :votes
has_many :users, through: :votes
validates :name, presence: true, uniqueness: true, :length => {
:minimum =>2,
:maximum =>50}
validates :url, presence: true
validates :description, presence: true
validates :downloads, numericality: { only_integer: true }
end
Run Code Online (Sandbox Code Playgroud)
new.html.erb
<%= form_for(@topgem) do |f| %>
<%= f.label :name %>:
<%= f.text_field :name %><br />
<%= f.label :url %>:
<%= f.text_field :url %><br />
<%= f.label :description %>:
<%= f.text_field :description %><br />
<%= f.label :downloads %>:
<%= f.number_field :downloads %><br />
<%= f.submit %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我得到的错误:
ActionController::ParameterMissing at /topgems
param is missing or the value is empty: name
Run Code Online (Sandbox Code Playgroud)
这是选择实例变量:
实例变量
@_action_has_layout
true
@_routes
nil
@_headers
{"Content-Type"=>"text/html"}
@_status
200
@_params
{"utf8"=>"?", "authenticity_token"=>"Gx/UwvcvWZYWAUHxWGYlUQB/PNNUniBpCjlM1WEHAm+luYl94Kky5Ae9Ur40YVtrN2ebEEX8C0G3Cewu/SJSow==", "topgem"=>{"name"=>"bfgf", "url"=>"dd", "description"=>"ff", "downloads"=>"343"}, "commit"=>"Create Topgem", "controller"=>"topgems", "action"=>"create"}
Run Code Online (Sandbox Code Playgroud)
你需要params[:name],但实际的参数是params[:topgem][:name].
将您的topgem_params方法更改为
params.require(:topgem).
permit(
:name,
:url,
:description,
:downloads,
:last_updated
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19890 次 |
| 最近记录: |