ruby-on-rails - 如何设置基本的 Rails 模型关联?
问题描述
大家好,我正在开发一个设计用户注册并登录的应用程序,一旦用户登录,他们就可以“创建团队”或“加入团队”。我的协会是这样建立的
用户.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
团队.rb
class Team < ApplicationRecord
has_many :users
end
我的桌子已经摆好了
架构.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 进行更新。或者当他们加入团队时。我的联想正确吗?我将如何在控制器中实现这一点?
解决方案
让我们将您的代码示例精简到所需的最低要求:
# app/models/team.rb
class Team < ApplicationRecord
has_many :users
end
# app/models/user.rb
class User < ApplicationRecord
belongs_to :team
end
# db/migrate/20181124230131_create_teams.rb
class CreateTeams < ActiveRecord::Migration[5.2]
def change
create_table :teams do |t|
t.string :team_name
t.timestamps
end
end
end
# db/migrate/20181124230136_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.belongs_to :team
t.timestamps
end
end
end
然后在你的控制器中:
team = Team.where(team_name: 'foo').first_or_create!
team.users << current_user
推荐阅读
- azure - Azure 函数未执行。每次都拒绝访问
- python - 在语义中引发异常后,是否可以继续使用其他规则进行解析?
- sql - 如何将以下 SQL 语句转换为更新语句
- git - 在自托管 git repo 上使用 git pull 请求的工作流程
- javascript - 窗口未定义,Vue 平滑滚动 - Nuxt.js
- firefox - Createjs 和 Firefox 72
- python - 是否有一种有效的方法来测试 .onion 链接是否有效
- python - MongoDB 不尊重上限集合的最大值
- android - Renderscript 如何从 2d 浮点数组初始化缓冲区以进行分配
- excel - Excel Tick Marks 改变数据显示