2015年3月13日 星期五

理解 posts_controller.rb

抓幾行來理解一下:

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

before_action 意思就是執行其它的action前要先執行指定的method,這裡就是set_post,
後面的only是限定要作用的action。

//////////////////////////////////////////////////////////////////

def index
    @posts = Post.all
end

進了Blog就是執行這個action,這裡把@posts設定好後,就會拿app/views/posts/index.html.erb
來顯示了。

//////////////////////////////////////////////////////////////////

def post_params
    params.require(:post).permit(:name, :title, :content)
end

params是http request所傳來一部份的值。
這可以取得post這個model的參數,後頭的permit是限定只取哪些參數

//////////////////////////////////////////////////////////////////

def create
    @post = Post.new(post_params) #取到的參數就可以實例化一個Post物件了。

//////////////////////////////////////////////////////////////////

respond_to do |format|
依請求的格式,返回不同的數據,如下:
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }

redirect_to和render是回應瀏覽器的方式
redirect_to @post 指示瀏覽器對一個 rul 再次發出請求,例如這邊是相當於讓瀏覽器執行 http://localhost:3000/posts/1 ,
render :show 就是把 show.html.erb 解析為html回傳給瀏覽器


沒有留言:

張貼留言