rails:用于加入/离开团队的用户按钮

时间:2012-07-31 08:29:45

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

目前,我得到两张桌子:

Users (with a foreign_key : team_id) 
Teams

关系:一对多(用户只能有一个团队,但团队车有很多用户)

Users :   belongs_to :teams
Teams:     has_many :users

class Team < ActiveRecord::Base
    has_many :users

class User < ActiveRecord::Base
  belongs_to :teams

配置/ routes.rb中

  get "users/new"
  resources :users
  resources teams do
    member do
      get 'join'
      get 'leave'
    end
  end
 resources :sessions, only: [:new, :create, :destroy]
   match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete

  match '/users', to: 'users#index'

  match '/teams', to: 'teams#index'
end

我尝试在团队页面上设置一个按钮(例如myapp/teams/1),用户(呼叫current_user)可以加入或离开此团队。

要加入一个团队,我们只需要更新列user.team_id并将其添加到团队的ID中(要离开团队,列user.team_id需要为空)。

任何人都有想法制作这两个按钮吗?

1 个答案:

答案 0 :(得分:2)

您的团队控制器需要两个操作。

def join
  @team = Team.find params[:id]
  current_user.update_attribute(:team_id, @team.id)
  redirect_to @team
end

def leave
  @team = Team.find params[:id]
  current_user.update_attribute(:team_id, nil)
  redirect_to @team
end

在路线

resources :teams do
  member do
    get 'join'
    get 'leave'
  end
end

以及展示视图中的链接

<%= link_to 'join', join_team_path(@team) %>
<%= link_to 'leave', leave_team_path(@team) %>

更新

请注意,此代码假设您的路由中已分别有resources :teams和团队控制器。如果没有,您需要进行一些修改。

更新

如果使用设计

,您还需要sign_in current_user