create controller ‘users’
cd railsdemo rails generate controller users index
Restart server. Then you can see.
create new.html.erb in app/views/users and add below code to create form
<%= form_for @user do |f| %> <div>name<%= f.text_field :name %></div> <div>comment<%= f.text_area :comment %></div> <div><%= f.submit "submit" %></div> <% end %>
Configure route as well. Add this line to config/routes.rb
This file will create form to put user data into database
but you have not created data table to register these data
Let’s create a Model to receive data.
rails generate model user
you can find this line when creating successfully
Then open this file.
Now you can see only the definition of the table.
t.string :name t.string :comment t.timestamps null: false
Now you made a form(View) and data(Model).
and you don’t have function to send data from form to database.
and add below
def new @user = User.new @users = User.all end def create @user = User.new(user_params) @user.save redirect_to :action => "new" end def user_params params.require(:user).permit(:name, :comment) end
controller has actions for each page.
This Model-View-Controller structure is called ‘MVC Model’.
Open the page and fill info and send.
Then, try to confirm registration
mysql -u root -p ~~put password~~ mysql>use railsdemo_development; ~~confirm your data~~
you can now register comments through form.
show it below that form.
you should use this expression.
<% @users.each do |user| %>
<% end %>
Now you created a simple application like twitter!