huntman's Blog

For Freedom

额外作业实作纪录 20170108

| Comments

实作 post 的 Edit 和 Delete 尼玛感觉好难啊,想了一个半钟还不知道要怎么做。差点去论坛看答案,还好我最后没放弃,把原来的 CRUD 拿出来对着改一遍试试,并且参照已有的 new 和 create 来增加 edit 、 update 和 destroy ,自己并没想着马上就 OK,结果竟然一次就 OK 了!怎么这么简单,我都无语了,之前自己非要想那么复杂~

 class PostsController < ApplicationController

  before_filter :authenticate_user!, only: [:new, :create]

  def new
    @group = Group.find(params[:group_id])
    @post = Post.new
  end

  def edit
    @group = Group.find(params[:group_id])
    @post = Post.find(params[:id])
    @post.user = current_user
  end


  def create
    @group = Group.find(params[:group_id])
    @post = Post.new(post_params)
    @post.group = @group   <#还没搞懂为什么要这行>
    @post.user = current_user
    if @post.save
      redirect_to group_path(@group)  <#这个路径也没搞懂意思>
    else
      render :new
    end
  end

  def update
    @group = Group.find(params[:group_id])
    @post = Post.find(params[:id])
    @post.user = current_user
    if @post.update(post_params)
      redirect_to group_path(@group), notice: 'Update Success'
    else
      render :edit
    end
  end


  def destroy
    @group = Group.find(params[:group_id])
    @post = Post.find(params[:id])
    @post.user = current_user
    @post.destroy

    redirect_to group_path(@group), alert: 'Post deleted'
  end


  private

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

end

Comments

comments powered by Disqus