Rails 同一模型中的自定义关系错误 has_many 和 has_one

Rails Custom relations error has_many and has_one in the same model

这是我的亲戚:

create_table :decks do |t|
    t.references :user, index: true
    t.string :name

    t.timestamps
end

create_table :users do |t|
    t.references :choosen_deck, index: true, foreign_key: { to_table: :decks }
    t.integer :hp
    t.integer :armor

    t.timestamps
end

关系:

=> user.rb

  has_many :decks, dependent: :destroy
  has_one :choosen_deck, class_name: 'Deck', dependent: :destroy

=> deck.rb

  belongs_to :user, foreign_key: 'user_id'
  belongs_to :choosen_deck, class_name: 'User'

这是我的迁移,我想要这样的关系:

=> user.choosen_deck

=> user.decks

=> deck.user

但它不起作用,因为我无法保存甲板模型。 你有什么想法吗?

更新:

=> 这是痕迹

2.4.1 :002 > d = Deck.new(name: "Deck t")
(0.5ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
=> #<Deck id: nil, user_id: nil, name: "Deck t", created_at: nil, updated_at: nil> 
2.4.1 :003 > u = User.new(hp: 20, armor: 20, choosen_deck: d)
=> #<User id: nil, choosen_deck_id: nil, hp: 20, armor: 20, created_at: nil, updated_at: nil> 
2.4.1 :004 > d.user
=> #<User id: nil, choosen_deck_id: nil, hp: 20, armor: 20, created_at: nil, updated_at: nil> 
2.4.1 :005 > d.save
(0.2ms)  BEGIN
User Create (0.3ms)  INSERT INTO `users` (`hp`, `armor`, `created_at`, `updated_at`) VALUES (20, 20, '2018-05-01 13:53:18', '2018-05-01 13:53:18')
Deck Create (0.2ms)  INSERT INTO `decks` (`user_id`, `name`, `created_at`, `updated_at`) VALUES (1, 'Deck t', '2018-05-01 13:53:18', '2018-05-01 13:53:18')
(5.7ms)  COMMIT
=> true 
2.4.1 :007 > d2 = Deck.create(name: "Deck 2", user: u)
(0.2ms)  BEGIN
Deck Create (0.3ms)  INSERT INTO `decks` (`user_id`, `name`, `created_at`, `updated_at`) VALUES (1, 'Deck 2', '2018-05-01 13:53:57', '2018-05-01 13:53:57')
(4.0ms)  COMMIT
=> #<Deck id: 2, user_id: 1, name: "Deck 2", created_at: "2018-05-01      13:53:57", updated_at: "2018-05-01 13:53:57"> 
2.4.1 :008 > u
=> #<User id: 1, choosen_deck_id: nil, hp: 20, armor: 20, created_at: "2018-05-01 13:53:18", updated_at: "2018-05-01 13:53:18"> 
2.4.1 :009 > u.choosen_deck
=> #<Deck id: 1, user_id: 1, name: "Deck t", created_at: "2018-05-01 13:53:18", updated_at: "2018-05-01 13:53:18"> 
2.4.1 :010 > u.save
(0.2ms)  BEGIN
(0.1ms)  COMMIT
=> true 
2.4.1 :011 > d.save
(0.2ms)  BEGIN
(0.2ms)  COMMIT
=> true 
2.4.1 :012 > d2.save
(0.2ms)  BEGIN
(0.1ms)  COMMIT
=> true 

祝你有愉快的一天

不应该只是:

class Deck < ActiveRecord::Base
  belongs_to :user
end

我不确定你的意图:

belongs_to :choosen_deck, class_name: 'User'

在创建记录方面,我认为您应该能够执行以下操作:

user = User.create!(hp: 20, armor: 20)
user.create_choosen_deck!(name: "Deck t")
user.decks.create!(name: "Deck 2")

create_choosen_deckdecks.create 是关联声明提供的方法(更多信息参见Docs)。如果您使用这些方法,则会自动设置 user_id 值。

(顺便说一句,它是 chosen,而不是 choosen。)