RoR - Restful Actions
Index:
用于检索所有条目
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。# 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
redirect_to:
# 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 %>

更多精彩