刘华佼的全栈学习记录

如何在前端增加“加入”或“退出”xxx的功能

| Comments

目标

在前端增加“加入”或“退出”xxx的功能

步骤一:

app/controllers/xxxs_controller.rb中加入join和quit的action:

  def join
   @xxx = xxx.find(params[:id])
  
    if !current_user.is_member_of?(@xxx)
      current_user.join!(@xxx)
      flash[:notice] = "加入本讨论版成功!"
    else
      flash[:warning] = "你已经是本讨论版成员了!"
    end
  
    redirect_to xxx_path(@xxx)
  end
  
  def quit
    @xxx = xxx.find(params[:id])
  
    if current_user.is_member_of?(@xxx)
      current_user.quit!(@xxx)
      flash[:alert] = "已退出本讨论版!"
    else
      flash[:warning] = "你不是本讨论版成员,怎么退出 XD"
    end
  
    redirect_to xxx_path(@xxx)
  end


步骤二:

限制加入和退出xxx必须要先登录才能操作:
app/controllers/xxxs_controller.rb中的before_action验证,加入join和quit:
before_action :authenticate_user! , only: [:new, :create, :edit, :update, :destroy, :join, :quit]

步骤三:

config/routes.rb改为:

  resources :groups do
     member do
        post :join
        post :quit
      end

      resources :posts
    end

步骤四:

app/views/xxxs/show.html.erb中成员和非成员标签后分别加入quit和join:

    <%= link_to("Quit xxx", quit_xxx_path(@xxx), method: :post, class: "btn btn-default") %>
  <% else %>

    <%= link_to("Join xxx", join_xxx_path(@xxx), method: :post, class: "btn btn-default") %>

Comments

comments powered by Disqus