目标很简单,创建一个带有名称和描述的文档以及附加的CSV文件。
我有以下迁移:
class CreateKeywords < ActiveRecord::Migration
def change
create_table :keywords do |t|
t.string :name, null: false, unique: true
t.string :description, null: false
t.string :keys, null: false
t.timestamps null: false
end
end
end
型号:
class Keyword < ActiveRecord::Base
mount_uploader :keys, KeywordsUploader
validates :name, :description, :keys, presence: true
validates :name, uniqueness: true
end
控制器:
class KeywordsController < ApplicationController
def index
@keywords = Keyword.all
end
def new
@keyword = Keyword.new
end
def create
puts "Keyword params"
pp keyword_params
@keyword = Keyword.new(keyword_params)
if @keyword.save
flash[:success] = "New server created!"
redirect_to @keyword
else
render 'new'
end
end
private
def keyword_params
params.permit(:keyword).permit(:name, :description, :keys)
end
end
最后查看:
<% provide(:title, 'Create keywords set') %>
<h1>New keywords set</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for @keyword, :html => {:multipart => true } do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_field :description %>
<%= f.label :keywords %>
<%= f.file_field :keys %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
当我尝试提交包含所有必填字段的表单时,我在视图中收到以下错误:
1) Name can't be blank
2) Description can't be blank
3) Keys can't be blank
在Rails控制台中,我可以在表单提交过程中看到以下内容:
Started POST "/keywords" for ::1 at 2015-10-09 17:21:40 +0300
Processing by KeywordsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"QO69fZ9xx1+mXRTL1TqZQLs9kYriQj4sqxV0t8P8XG2nu1FvKmOw6fISpmvi70VlWrD9bCJg7bCqwLwUfvwGRQ==", "keyword"=>{"name"=>"asd", "description"=>"asd"}, "commit"=>"Create keywords"}
Keyword params
Unpermitted parameters: utf8, authenticity_token, keyword, commit
{}
Unpermitted parameters: utf8, authenticity_token, keyword, commit
正如您所看到的,强params函数返回一个空哈希,并且 这就是为什么不可能创建模型“关键字”的实例。
可能有什么问题?
答案 0 :(得分:1)
解决!
而不是使用:
def keyword_params
params.permit(:keyword).permit(:name, :description, :keys)
end
我应该一直在使用:
def keyword_params
params.require(:keyword).permit(:name, :description, :keys)
end
问题是由不正确的keyword_params方法引起的。