【问题标题】:Associations Setup Correctly Results in a Uninitialized Constant关联设置正确导致未初始化的常量
【发布时间】:2020-12-19 07:44:02
【问题描述】:

我在UserStakeUserStake 之间有一个简单的many_to_many 关系,一切似乎都设置正确,但结果是NameError (uninitialized constant User::Stakes)

#db/schema.rb
ActiveRecord::Schema.define(version: 2020_12_19_070749) do

  create_table "stakes", force: :cascade do |t|
    t.string "address"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "user_stakes", force: :cascade do |t|
    t.integer "user_id"
    t.integer "stake_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "password_digest"
  end

end
#app/models/stake.rb
class Stake < ApplicationRecord
    has_many :active_stakes
    has_many :user_stakes
    has_many :users, through: :user_stakes
end

#app/models/user.rb
class User < ApplicationRecord
    has_many :user_stakes
    has_many :stakes, through: :user_stakes
    
    has_secure_password
end

#app/models/user_stake.rb
class UserStake < ApplicationRecord
    belongs_to :users
    belongs_to :stakes
end

当我通过rails c 尝试关联时,出现以下错误NameError (uninitialized constant User::Stakes)

2.6.3 :019 > s
 => #<Stake id: 310524, address: "stake1u8003gtvhcunzzmy85nfnk6kafd8lks2mykfzf0n4hq4...", created_at: "2020-12-08 12:08:25", updated_at: "2020-12-08 12:08:25"> 
2.6.3 :020 > u
 => #<User id: 21, username: "s324xexd", created_at: "2020-12-19 00:16:31", updated_at: "2020-12-19 00:16:31", password_digest: [FILTERED]> 
2.6.3 :021 > u.stakes << s
Traceback (most recent call last):
        1: from (irb):21
NameError (uninitialized constant User::Stakes)
2.6.3 :022 > u.stakes
Traceback (most recent call last):
        2: from (irb):22
        1: from (irb):22:in `rescue in irb_binding'
NameError (uninitialized constant User::Stakes)

【问题讨论】:

    标签: ruby-on-rails ruby many-to-many associations


    【解决方案1】:

    belongs_to 关联必须使用单数术语。

    #app/models/user_stake.rb
    class UserStake < ApplicationRecord
        belongs_to :user
        belongs_to :stake
    end
    

    The belongs_to Association

    belongs_to 关联必须使用单数术语。如果你在上面的例子中使用复数形式作为 Book 模型中的作者关联,并尝试通过 Book.create(authors:@author) 创建实例,你会被告知有一个“未初始化的常量 Book::Authors ”。这是因为 Rails 会自动从关联名称中推断出类名称。如果关联名称的复数错误,那么推断的类也会错误的复数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多