【问题标题】:A class was passed to `:class_name` but we are expecting a string一个类被传递给 `:class_name` 但我们期待一个字符串
【发布时间】:2019-03-06 03:16:31
【问题描述】:

我正在尝试创建一个名为 :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

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

我的模型如下所示:

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

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

未初始化的常量 Book::Claim

我试图在命名foreign_key_association之后在模型中的hmbtm关系中指定,我做了一个class_name:ClassName,认为这可能会解决这个错误,但我得到一个新的说A class was passed to @ 987654323@ 但我们需要一个字符串。

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

【问题讨论】:

    标签: ruby-on-rails arrays associations has-and-belongs-to-many jointable


    【解决方案1】:

    错误提示您应该将字符串作为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
    

    或:

    class Foo < AR
      has_many :bars, class: Baz # returns the class
    end
    

    【讨论】:

    • 谢谢!感谢快速回答。很高兴这是一个简单的修复,没有更多错误。
    • 还有一个简短的说明,class 从 Rails 6.0.0 开始不再工作。 Unable to load application: ArgumentError: Unknown key: :class. Valid keys are: :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, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors
    • 这是不推荐使用常量化类的拉取请求:github.com/rails/rails/pull/27551。为了便于阅读,我建议使用class_name: Baz.name 来返回Baz 的字符串化版本。
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多