RoR - Restful Actions

时间:2021-05-27 05:07:02

Index:

用于检索所有条目

# index.json.jbuilder 

json.array!(@post) do |post|
json.extract! post, :id, :title, :content
json.url post_url(post, format: :json)
end #/posts.json

Show&Destory:

1.根据id检索相应的条目

2.跳转到show.html.erb 提供相应

#example

localhost:3000/posts/1

#show.json.jbuilder 

json.extract! @post, :id, :title, :content, :created_at, :updated_at

localhost:3000/posts/2.json 

respond_to:  特定怎么去相应一个request

RoR - Restful Actions

redirect_to:

RoR - Restful Actions

# DELETE /posts/1
# DELETE /posts/1.json def destory
@post.destory
respond_to do |format|
format.html {redirect_ to posts_url, notice: 'Post deleted' }
format.json {head :no_content }
end
end

New&Create:

# GET /posts/new

def new
@post = Post.new
end # Look for new.html.erb

Create Action 没有模板,它会试着将object存进数据库,如果成功的话重定向到show 模板

如果没有成功render new action

Flash:

# flash 

flash[:attribute] = value 

# :notice (good)  :alert (bad)
  

edit:

# GET /posts/1/edit 

before_action :set_post, only: [:show, :edit, :update, :destory]

def edit 

end 

private
def set_post
@psot = Post.find(params[:id])
end
end

update:

用id检索到需要update的object

用edit form里面的parameters去更新object

保存更新的数据到数据库

(默认)成功的话,重定向到show 模板

不成功,到edit

before_action :set_post, only: [:show, :edit, :update, :destory]

# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json def update
respond_to do |format|
if @post.update(post_params)
format.html {redirect_to @post, notice: 'Post was updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity}
end
end
end private
def set_post
@psot = Post.find(params[:id])
end def post_params
params.require(:post).permit(:title, :content)
end
end

Partials:

# partial start with _

<%= render @posts %> 

is equivalent to 

<% @posts.each do |post| %>
<%= render post %>
<% end %>

Form Helpers and Layouts:

<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<% end %> <div class="field">
<%= f.label :title %> <br>
<%= t.text_field :title %>
</div> <div class="field">
<%= f.label :content %> <br>
<%= f.text_area :content %>
</div> <div class= "actions">
<%= f.submit %>
</div>
<% end %>

如果想在controller里用model里的method,

首先defind self.method 在model里

接着用model.method 在controller里面