如何让一个Rails型号在一个表中有多个user_id? [英] How to have a rails model have mulitple user_id's in one table?
问题描述
我正在开发一个分配系统。我需要能够访问分配给比赛模型的裁判。分配最多可以有4名全部为用户的推荐人。我相信我的联想是正确的。我的问题是:
是否需要将assignment_id添加到游戏表?
要测试我的系统,我最终需要设定数据种子。如何播种数据/设置分配,以使每个属性(center_referee、assistant_referee)都是用户?如果此表单有作用,我希望它不可避免地成为一个下拉列表。
对于种子数据,我查找的内容大致如下(忽略我使用的是
name
而不是first_name
):
Assignment.create(center_referee: user.name, assistant_referee_1: user.name, assistant_referee_2: "user.name", fourth_official: "user.name", game_id: 1)
- 是否需要在模型关联上设置
accepts_nested_attributes
才能完成所有这些操作?
型号:
class User < ApplicationRecord
has_many :assignments
has_many :games, through: :assignments
end
class Game < ApplicationRecord
has_one :assignment
has_many :users, through: :assignments
end
class Assignment < ApplicationRecord
belongs_to :game
belongs_to :user
end
架构:
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "first_name"
t.string "last_name"
t.string "role"
end
create_table "games", force: :cascade do |t|
t.string "home_team"
t.string "away_team"
end
create_table "assignments", force: :cascade do |t|
t.string "center_referee"
t.string "assistant_referee_1"
t.string "assistant_referee_2"
t.string "fourth_official"
t.integer "game_id"
end
我知道这是一个有点沉重的问题,但我对这个问题已经绞尽脑汁好一段时间了。
推荐答案
我想补充@vijay所说的
由于您希望在单个表中有多个user_id,我建议您将关联命名为,例如:inassignment.rb
Asbelongs_to :center_referee, class_name: 'User'
您还可以使用optional: true
将关联保持为可选。
是否需要将assignment_id添加到游戏表?
否,此处Assignment belongs_to Game
因此id应该存在于分配模型中(因为分配没有游戏就不能存在,但是游戏独立于分配)。
如果这是关于访问给定游戏的任务,您可以尝试game.assignment
。
是否需要在模型关联上设置ACCEPTIONS_NESTED_ATTRIBUTES才能完成所有这些操作?
accepts_nested_attributes
如果您希望在接受模型属性(游戏)的同时接受关联模型的属性(赋值),则使用accepts_nested_attributes
。
有关详细信息checkout
我不太明白您的问题,但请查看此问题是否有帮助:要测试我的系统,我最终将需要设定数据种子。如何播种数据/设置分配,以使每个属性(center_referee、assistant_referee)都是用户?如果此表单有作用,我希望它不可避免地成为一个下拉列表。
f.collection_select(:center_referee_id, User.all, :id, :name )
希望这对您有帮助。
这篇关于如何让一个Rails型号在一个表中有多个user_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!