在控制器中获取缺少的参数信息。这是控制器的代码
class SubjectsController < ApplicationController
layout false
def new
@subject=Subject.new
end
def create
@subject = Subject.create(subject_params)
if @subject.save
redirect_to(:action => 'index')
else
render('new')
end
end
private
def subject_params
params.require(:subject).permit(:name, :position, :visible)
end
end
这是new.html.erb的代码
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="subjects new">
<h2>Create Subject</h2>
<%= form_for(:subject, :url => {:action => 'create'}) do |f| %>
<table summary="Subject form fields">
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th>Position</th>
<td><%= f.text_field(:position) %></td>
</tr>
<tr>
<th>Visible</th>
<td><%= f.text_field(:visible) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Create Subject") %>
</div>
<% end %>
</div>
希望有人能够告诉我为什么会收到此错误:
ActionController::ParameterMissing in SubjectsController#create
param is missing or the value is empty: subject
Extracted source (around line #34):
def subject_params
params.require(:subject).permit(:name, :position, :visible)
end
end
由于
答案 0 :(得分:1)
请尝试以下代码。这似乎也适用于rails 4。
#app/views/subjects/_form.html.erb
<%= form_for(@subject) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :position %><br>
<%= f.text_field :position %>
</div>
<div class="field">
<%= f.label :visible %><br>
<%= f.text_field :visible %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
#app/controllers/subjects_controller.rb
class SubjectsController < ApplicationController
layout false
def new
@subject = Subject.new
end
def index
@subjects = Subject.all
end
def create
@subject = Subject.new(subject_params)
if @subject.save
redirect_to subjects_path
else
render :new
end
end
private
def subject_params
params.require(:subject).permit(:name, :position, :visible)
end
end
检查控制台输出:
答案 1 :(得分:1)
你可以试试这个
class SubjectsController < ApplicationController
layout false
def index
@subjects = Subject.scoped
end
def new
@subject=Subject.new
end
def create
@subject = Subject.new(subject_params)
if @subject.save
redirect_to(:action => 'index')
else
render('new')
end
end
private
def subject_params
params.require(:subject).permit(:name, :position, :visible)
end
end
在视图中
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="subjects new">
<h2>Create Subject</h2>
<%= form_for @subject do |f| %>
<table summary="Subject form fields">
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th>Position</th>
<td><%= f.text_field(:position) %></td>
</tr>
<tr>
<th>Visible</th>
<td><%= f.text_field(:visible) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Create Subject") %>
</div>
<% end %>
</div>
在路线/config/routes.rb
resources :subjects