Here's a very quick and very simple Rails form. I am pulling this from this Youtube tutorial, but documenting the actual steps needed because I find it easier to read and newer versions of Rails require that we do things a little differently than what is described in the video.
cd rails_projects
rails new simpleform
cd simpleform
rails g controller students
rails g model Student firstname:string lastname:string
rake db:migrate
cd db
sqlite3 development.sqlite3
.schema
.quit
cd ..
Change app/controllers/students_controller.rb from this:
class StudentsController < ApplicationController
end
To this:
class StudentsController < ApplicationController
def new
@student = Student.new
end
def create
@student = Student.new(params[:student])
if @student.save
redirect_to new_student_path
end
end
end
Create new file app/views/students/new.html.erb:
Enter new student information
<hr>
<%= form_for @student do |f| -%>
Firstname: <%= f.text_field :firstname %><br />
Lastname: <%= f.text_field :lastname %><br />
<%= f.submit %>
<% end -%>
Insert the resources line into config/routes.rb:
Simpleform::Application.routes.draw do
resources :students
Start up the rails server to see how things look thus far:
rails s
Point your browser to http://localhost:3000/students/new
This shows you a simple form with text fields for firstname and lastname. Enter in some text for the two fields and click the submit button. You will get an error:
ActiveModel::ForbiddenAttributesError in StudentsController#create
ActiveModel::ForbiddenAttributesError
Extracted source (around line #7):
@student = Student.new(params[:student])
I think it has to do with security and probably a change that happened in Rails versions.
Here's the fix.
Change app/controllers/students_controller.rb:
class StudentsController < ApplicationController
def new
@student = Student.new
end
def create
@student = Student.new(user_params)
if @student.save
redirect_to new_student_path
end
end
private
def user_params
params.require(:student).permit(:lastname, :firstname)
end
end
Now point your browser to http://localhost:3000/students/new
and try to enter a couple records.
We can view the new records in our database:
cd db
sqlite3 development.sqlite3
.schema
select * from students;
.quit
cd ..
So we are successfully inserting data into our database! Hurray!
Now we will make a couple changes so our web page not only gathers student names, but displays them as well.
Append the following lines to app/views/students/new.html.erb:
<hr>
Display all students' information<br />
<% if !@students.blank? %>
<% for item in @students %>
<%= item.firstname %> <%= item.lastname %> <br />
<% end %>
<% else %>
<% end %>
We also have to define @students in app/controllers/students_controller.rb:
def new
@student = Student.new
@students = Student.find(:all)
end
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.