0

Currently, I get two tables :

Users (with a foreign_key : team_id) 
Teams

Relationships : one-to-many (a user can have only 1 team, but a team car have many users)

Users :   belongs_to :teams
Teams:     has_many :users

class Team < ActiveRecord::Base
    has_many :users

class User < ActiveRecord::Base
  belongs_to :teams

config/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

And I try to make a button on the team page (e.g. myapp/teams/1) where a user (who call current_user) can join or leave this team.

To join a team we just have to update the column user.team_id and put on this the id of the team (to leave a team, the column user.team_id need to be empty).

Anyone have an idea to make these two buttons?

4

1 回答 1

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如果使用设计,您还需要

于 2012-07-31T09:04:43.297 回答