go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Traffic flow
 
Subject: Traffic flow
Author: Linux
In response to: Step 6 -- Save data into database
Posted on: 09/13/2017 04:50:40 AM

Type into your browser: http://localhost:3000/blog/new

New Post

Title
[               ]

Text
[               ]

[Save Post]


Typing title and text and clicking on Save Post button should bring: http://localhost:3000/posts/1
Title: Post #2

Text: This is my second post.


You can also verify the data persistence in database:
administrator@ubuntu:~/blog$  psql -h localhost -p 5432 -U blog_admin blog_development

Password for user blog_admin: 
psql (9.6.5, server 9.3.19)
SSL connection (protocol: TLSv1.2, cipher: DHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

blog_development=> SELECT * FROM posts;

 id |   title  |  text  |  created_at  |  updated_at         
----+----------+--------+--------------+-------------------
  1 | Post#1   | This...| 2017-09-13 04:21:15.40803  | 2017-09-13 04:21:15.40803
  2 | Post#2   | This...| 2017-09-13 04:25:12.514606 | 2017-09-13 04:25:12.514606
(2 rows)



 

> On 09/13/2017 04:28:18 AM Linux wrote:


Back to the controller app/controllers/posts_controller.rb, change the content of action create
class PostsController < ApplicationController
 
  def new
  end

  def create
    @post = Post.new(params[post_params]) 
    @post.save
    redirect_to @post
  end
 
  def show
    @post = Post.find(params[:id])
  end

  private
    def post_params
      params.require(:post).permit(:title, :text)
    end

end


This is going to do:
  • Initialize the model Post with params from its respective attributes
  • @post.save -- Save the model into it corresponding table posts
  • redirect_to @post -- redirect the view to show
  • require().permit() -- allow rights

    Showing the post

    app/views/posts/show.html.erb
    <p>
      <strong>Title:</strong>
      <%= @post.title %>
    </p>
     
    <p>
      <strong>Text:</strong>
      <%= @post.text %>
    </p>
    





    References:

  •  


     
    Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
     
    Get your own forum today. It's easy and free.