我希望模型Game
有两个用户:user1
和user2
这是我的两个模型及其迁移:
game.rb:
class Game < ApplicationRecord
has_secure_token
# @!group RELATIONS
has_many :turns, dependent: :destroy
has_many :play_cards, dependent: :destroy
has_one :user1, class_name: 'User', dependent: :destroy
has_one :user2, class_name: 'User', dependent: :destroy
# @!endgroup
# @!group VALIDATORS
validates :user1_id, presence: true, blank: false, nill: false
validates :user2_id, presence: true, blank: false, nill: false
validates :finish_at, presence: true, blank: false, nill: false
validates :token, presence: true, blank: false, nill: false, length: { is: 24 }
# @!endgroup
end
迁移:
def change
create_table :games do |t|
t.references :user1, foreign_key: { to_table: :users }
t.references :user2, foreign_key: { to_table: :users }
t.string :token, length: { is: 24 }, null: false
t.datetime :finish_at, null: false
t.timestamps
end
end
user.rb:
class User < ApplicationRecord
has_secure_token :token
# @!group RELATIONS
has_many :decks, dependent: :destroy
has_one :chosen_deck, class_name: 'Deck', dependent: :destroy
has_many :turns, dependent: :destroy
# @!endgroup
# @!group VALIDATORS
validates :hp, presence: true, blank: false, nill: false, numericality: { greater_than_or_equal_to: 0 }
validates :armor, presence: true, blank: false, nill: false, numericality: { greater_than_or_equal_to: 0 }
validates :token, presence: true, blank: false, nill: false, length: { is: 24 }, on: :save
validates :name, presence: true, blank: false, nill: false, length: { minimum: 4 }
# @!endgroup
end
迁移:
create_table :users do |t|
t.references :chosen_deck, index: true, foreign_key: { to_table: :decks }
t.string :name, null: false
t.integer :hp, null: false, default: 20
t.integer :armor, null: false, default: 0
t.string :token, length: { is: 24 }, null: false
t.timestamps
end
当我尝试使用该游戏保存游戏时,会出现问题:
ActiveModel::MissingAttributeError: can't write unknown attribute `game_id`
我在此处放置了一个屏幕截图:error screen
度过愉快的一天,
答案 0 :(得分:4)
ActiveModel :: MissingAttributeError:无法写入未知属性
game_id
问题在于错误所在。 User
模型缺少game_id
属性,这是约定用于连接用户和游戏所必需的(如果您想要另一列,则应明确指定为foreign_key)
只需为game_id
创建users
列,并在belongs_to :game
模型中指定(不必要)User
,因为用户belongs_to
是游戏。
否则,由于您有user1_id
和user2_id
,因此您需要将has_one
更改为belongs_to
。然后,它会更新这些belongs_to
列,而不是在game_id
关联中查找has_one
。
class Game < ApplicationRecord
# @!group RELATIONS
has_many :turns, dependent: :destroy
has_many :play_cards, dependent: :destroy
belongs_to :user1, class_name: 'User', dependent: :destroy
belongs_to :user2, class_name: 'User', dependent: :destroy
# @!endgroup
end