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但我们期待一个字符串。
我真的很困惑,需要有人向我解释这一点。谢谢!
该错误表示您应该将字符串作为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)
| 归档时间: |
|
| 查看次数: |
2582 次 |
| 最近记录: |