首页 > 解决方案 > 如何设置基本的 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 进行更新。或者当他们加入团队时。我的联想正确吗?我将如何在控制器中实现这一点?

标签: ruby-on-railsruby

解决方案


让我们将您的代码示例精简到所需的最低要求:

# 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

推荐阅读