我在另外 1 次发布过,但它仍然无法正常工作,尽管尝试了 3 个小时,但我无法弄清楚原因。我对这一切都很陌生,这对我来说非常复杂。我真的很感激这方面的一些帮助。谢谢!
我需要创建一个用户团队。一个用户belongs_to
一个团队,一个团队has_many
用户。
用户应该能够创建团队、加入现有团队、退出当前团队(如果你能告诉我如何让创建团队的人成为团队领导者,那也很棒!)
我有这样设置的数据库表:
- 用户表:
id, name, email, timestamps, team_id
- 团队表:
id, team_name, timestamps, user_id
我得到的错误:
undefined method `team_build' for #<User:0x3a14a80>
1: <%= button_to "Join", join_teams_path(current_user.team.build(team_id: @team_id)), class: "btn btn-large btn-primary" %>
用户型号:
class User < ActiveRecord::Base
attr_accessible :company, :name, :email, :password, :password_confirmation, :image
belongs_to :team, dependent: :destroy
validates :user_id, presence: true
def team_member?
team.present?
end
def join!(team)
return false if team_member?
team.create!(team_id: team.id)
end
def unjoin!(team)
return if team_member?
team.destroy
end
团队模型:
class Team < ActiveRecord::Base
has_many :users
attr_accessible :team_name
before_save { |team| team.team_name = team_name.downcase }
validates :team_name,
presence: true,
length: { maximum: 140 },
uniqueness: { case_sensitive: false }
default_scope order: 'teams.created_at DESC'
end
团队控制器:
class TeamsController < ApplicationController
before_filter :signed_in_user
def join
@team = Team.find params[:id]
if current_user.join!(@team.id)
redirect_to @user #NOTE dont use redirect when you perform actions with ajax.
else
#render some error
end
end
def show
@team = Team.find(params[:id])
end
def leave
if current_user.unjoin!
redirect_to @user #NOTE dont use redirect when you perform actions with ajax.
else
#render some error
end
end
def new
@team = Team.new
end
def create
@team = Team.new(params[:team])
if @team.save
flash[:success] = "Team Created!"
redirect_to @team
else
render 'new'
end
end
def teams
@title = "Teams"
@team = Teams.find(params[:id])
render 'show_teams'
end
def index
Team.all
end
加入按钮:
<%= button_to "Join", join_teams_path(current_user.team.build(team_id: @team_id)), class: "btn btn-large btn-primary" %>
取消加入按钮:
<%= button_to "Leave Team", leave_teams_path(current_user.team) , class: "btn btn-large btn-primary" , remote: true %>
路线:
resources :teams
match '/teams', to: 'teams#index'
match '/new_team', to: 'teams#new'