Create a web app that can do CRUD (create, read, update, delete) like the most basic Twitter app.
$ rails g model Post content:text
//rails g model table name(Singular)Column name:Data type(What kind of data will be entered)
$ rails db:migrate
//Reflect the contents of the migration file = table(DB)Can
The table name is singular.
$ rails console
> post = Post.new(content:"Hello World")
//Create a "post instance" with content of Hello World
> post.save
> posts = Post.all
> posts[0] //posts[0]Can be confirmed
In the action index in the posts controller, Create a function index that receives the contents of the blog from the table.
class PostsController < ApplicationController
def index
@posts = Post.all
# @posts = [
# "I'm studying Rails from today!",
# "Post list page is being created!",
# "I ate a snack today!",
# "I want to eat chocolate",
# "It was sunny after a long time today"
# ]
end
end
If you add @ to the variable, you can access it from other files, so use @posts
. It can be displayed in html like this.
<div class="container">
<% @posts.each do |post| %>
<div class="posts-index-item">
<%=post.content %>
</div>
<% end %>
When css is arranged, it looks like this. I was able to add it from the rails console! !! !! !!
Write the HTML you want to display on any page in application.html.erb Like the header.
Write this in html with <li> </ li>
.
<%=link_to("TweetApp","/") %>
$ rails console
> post = Post.find_by(id: 3)
> post.content
> post.created_at #Posting time
Route
#Post detail page routing
get "posts/:id" => "posts#show"
form_tag method
<%=form_tag(url)%>
<%end%>
redirect_to method
def create
redirect_to("/posts/index")
end
<%=form_tag("/posts/create")%>
<div class="form">
<div class="form-body">
<textarea name="content"></textarea>
<input type="submit" value="Post">
</div>
</div>
<%end%>
Since it is saved as content: (posted content)
in a hash table called params,
New, save and redirect as below
#Add create action
def create
@post = Post.new(content: params[:content])
@post.save
redirect_to("/posts/index")
end
rails console
> post = Post.find_by(id: 1)
> post.content = "apple" #Overwrite
> post.save
rails console
> post = Post.find_by(id: 1)
> post.destroy
Recommended Posts