Reputation: 5892
I'm following some Ruby on Rails tutorials, and I'm just simply trying to use the create method.
Here's my subjects controller:
class SubjectsController < ApplicationController
def index
end
def list
@subjects = Subject.order("subjects.position ASC")
end
def show
@subject = Subject.find(params[:id])
end
def new
@subject = Subject.new(:name => 'Default')
end
def create
@subject = Subject.new(params[:subject])
if @subject.save
redirect_to(:action => 'list')
else
render('new')
end
end
end
and here's the new.html.erb file:
<%= link_to("<< Back to list", {:action => 'list'}, :class => 'back-link') %>
<div class="subject 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(:visib) %></td>
</tr>
</table>
<div class="form buttons">
<%= submit_tag("Create Subject") %>
</div>
<% end %>
</div>
So when I go the localhost:3000/controller/new, I can see the form that shows the textfields just as I expect. However, the minute I try to submit it, I get to an error page that gives an ActiveModel::ForbiddenAttributesError error.
Here's the parameters that were submitted to the create action:
{"utf8"=>"✓",
"authenticity_token"=>"rwzPJd9HG5p/F8Uz7iktOa2hOnmQdwYFoZTqKSskDbU=",
"subject"=>{"name"=>"nothing",
"position"=>"5",
"visible"=>"false"},
"commit"=>"Create Subject"}
If I went into rails console, then everything works fine if I try to do this exact same thing manually (I think at least?).
2.1.1 :016 > Subject.create({"name"=>"nothing",
2.1.1 :017 > "position"=>"5",
2.1.1 :018 > "visible"=>"false"})
(0.6ms) BEGIN
SQL (3.2ms) INSERT INTO `subjects` (`created_at`, `name`, `position`, `updated_at`) VALUES ('2014-06-06 02:08:38', 'nothing', 5, '2014-06-06 02:08:38')
(1.4ms) COMMIT
=> #<Subject id: 11, name: "nothing", position: 5, visible: false, created_at: "2014-06-06 02:08:38", updated_at: "2014-06-06 02:08:38">
I'm still new to Rails.
Upvotes: 0
Views: 163
Reputation: 33542
You should be doing it like this
class SubjectsController < ApplicationController
........
........
def create
@subject = Subject.new(subject_params)
if @subject.save
redirect_to(:action => 'list')
else
render('new')
end
end
private
def subject_params
params.require.(:subject).permit(:name,:visible,:position)
end
end
Have a look at Strong Parameters
here in these Guides
Upvotes: 1