一个类被传递给`:class_name`,但我们期待一个字符串

dmb*_*o11 2 arrays ruby-on-rails associations has-and-belongs-to-many jointable

我正在尝试创建一个名为 :books_users 的连接表,其中书籍中的一列 :claim 是一个布尔值,如果有人单击“查看此书”的链接,则书籍控制器中的声明操作会执行以下操作:

def claim
    book = Book.find(params[:id])
    book.claims << current_user unless book.claims.include?(current_user)
    redirect_to current_user
    flash[:notice] = "You have a new book to review!"
  end
Run Code Online (Sandbox Code Playgroud)

这样做的目的是让我的用户注册为评论者可以进入图书展示页面,如果他们决定评论评论者通过流派找到的作者上传的书?然后他们基本上表明他们要评论那本书,他们的评论最终将作为经过验证的购买评论显示在亚马逊上,而不是书籍显示页面上网站上的俗气文本评论(这将使注册的作者审核服务很开心)。

我的模型看起来像这样:

book.rb 

class Book < ApplicationRecord
  mount_uploader :avatar, AvatarUploader
  belongs_to :user
  has_and_belongs_to_many :genres
  has_and_belongs_to_many :claims, join_table: :books_users, association_foreign_key: :user_id

end

user.rb

class User < ApplicationRecord
mount_uploader :avatar, AvatarUploader

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :books
  enum access_level: [:author, :reviewer]

  has_and_belongs_to_many :claims, join_table: :books_users, association_foreign_key: :book_id
end
Run Code Online (Sandbox Code Playgroud)

当审阅者单击链接以审阅这本书时,我在 BooksController#claim 中收到 NameError

未初始化的常量 Book::Claim

我试图在命名foreign_key_association后在模型中的hmbtm关系中指定,我做了一个class_name:ClassName,认为这可能会解决错误,但我得到一个新的说A类被传递给:class_name但我们期待一个字符串。

我真的很困惑,需要有人向我解释这一点。谢谢!

Зел*_*ный 5

该错误表示您应该将字符串作为class_name参数传递,或者您可以使用未记录的class选项:

class Foo < AR
  has_many :bars, class_name: to_s 
  # to_s returns the class name as string the same as Bar.class.to_s
end
Run Code Online (Sandbox Code Playgroud)

或者:

class Foo < AR
  has_many :bars, class: Baz # returns the class
end
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,从 Rails 6.0.0 开始,“class”不再起作用。`无法加载应用程序:ArgumentError:未知密钥::class。有效键为: :class_name、 :anonymous_class、 :foreign_key、 :validate、 :autosave、 :table_name、 :before_add、 :after_add、 :before_remove、 :after_remove、 :extend、 :primary_key、 :dependent、 :as、 :through、 :源,:source_type,:inverse_of,:counter_cache,:join_table,:foreign_type,:index_errors` (2认同)
  • 以下是不推荐采用常量化类的拉取请求:https://github.com/rails/rails/pull/27551。出于可读性目的,我建议使用 `class_name: Baz.name` 来返回 `Baz` 的字符串化版本。 (2认同)