我正在为创建"Projects"的表单而苦苦挣扎。最终,我想只允许当前的user_id,但我还没有建立用户模型或身份验证,所以作为占位符,我只是对1
进行硬编码。
app/views/projects/new.html.erb:
<%= form_for(:project, :url => {:action=>'create'}) do |f| %>
<%= f.text_field(:name) %>
<%= f.text_field(:instructions) %>
<%= f.hidden_field( :user_id, {:value=>1}) %>
<%= f.submit('Create Project') %>
<% end %>
app/controllers/projects_controller.rb
def create
#save object
if Project.create( project_params )
redirect_to(:action=>'show')
else
render('new')
end
end
private
def project_params
params.require(:project).permit({:user_id => [1]}, :instructions, :max_duration, :active, :max_videos, :hashed_id)
end
以下是我尝试提交表单时遇到的错误:
Mysql2::Error: Field 'user_id' doesn't have a default value: INSERT INTO `projects` (`created_at`, `instructions`, `updated_at`) VALUES ('2013-08-16 17:38:56', 'sdfgsdf', '2013-08-16 17:38:56')
看起来project_params()方法正在剥离user_id。我做错了什么?
可能是因为params[:user_id]是一个字符串,所以这样做应该有效。
params.require(:project).permit({:user_id => ["1"]}, :instructions, :max_duration, :active, :max_videos, :hashed_id)