【发布时间】:2018-11-25 18:52:20
【问题描述】:
大家好,我正在开发一个设计用户注册并登录的应用程序,一旦用户登录,他们就可以“创建团队”或“加入团队”。我的协会是这样设置的
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
validates_presence_of :phone, :city, :state, :street, :zip, presence: true, on: :create
belongs_to :team
end
team.rb
class Team < ApplicationRecord
has_many :users
end
我的桌子已经布置好了
schema.rb
create_table "teams", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "team_name"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "firstname"
t.integer "team_id"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
team_controller.rb
class TeamController < ApplicationController
before_action :authenticate_user!
def index
@team = current_user.team
end
def new_team
end
def create_team
@team = current_user.create_team(sanitize_team)
if @team.save
redirect_to team_root_path
else
render json: @team.errors.full_messages
end
end
def join_team
@teams = Team.all
end
def team
end
private
def sanitize_team
params.require(:team).permit(:team_name, :team_statement)
end
end
我希望用户的“team_id”属性在创建团队时使用团队 ID 进行更新。或者当他们加入团队时。我的联想正确吗?我将如何在控制器中实现这一点?
【问题讨论】:
-
您的路线是什么样的?您是否使用 Rail 的默认 RESTful 路由(即您的 routes.rb 文件中的
resources :teams?不需要创建诸如 new_team、create_team 等操作。相反,团队将由控制器的名称暗示,您应该简单地拥有新建、创建等操作。
标签: ruby-on-rails ruby