我试图建立一个简单的域来练习更好地建立Ruby关系。在这方面,作者可以有很多书,但一本书只能有一个作者。书籍有很多字符,可以出现在多本书中。这很好。它是我努力奋斗的人物关系的作者。当我尝试访问character.author
时,我得到nil
。 author.characters
返回一个包含重复项的列表 - 七个哈利波特,每本书一个。理想情况下,我希望rowling.characters
返回一个只有一个哈利波特的清单(我们不会逃离女贞路),显然harry.author
返回JK罗琳的实例。
author.rb
class Author < ActiveRecord::Base
has_many :books
has_many :characters, through: :books
end
book.rb
class Book < ActiveRecord::Base
belongs_to :author
has_and_belongs_to_many :characters
end
character.rb
class Character < ActiveRecord::Base
has_and_belongs_to_many :books
belongs_to :author, through: :books
end
schema.rb
ActiveRecord::Schema.define(version: 2018_06_18_134335) do
create_table "authors", force: :cascade do |t|
t.string "name"
t.string "pen_name"
end
create_table "books", force: :cascade do |t|
t.string "title"
t.integer "author_id"
end
create_table "books_characters", force: :cascade do |t|
t.integer "book_id"
t.integer "character_id"
end
create_table "characters", force: :cascade do |t|
t.string "name"
t.string "author_id"
end
end
答案 0 :(得分:1)
这是你可能想要的东西:
author.rb
set-buffer-file-coding-system
如果在rails 4上你将使用uniq而不是distinct。
book.rb
class Author < ActiveRecord::Base
has_many :books
has_many :characters, -> {distinct}, through: :books
end
book_character.rb
class Book < ActiveRecord::Base
belongs_to :author
has_many :book_characters
has_many :characters, through: :book_characters
end
character.rb
class BookCharacter < ActiveRecord::Base
belongs_to :book
belongs_to :character
end
这实际上说明了您收到的所有评论,并以更清洁的方式进行了评论。它允许角色拥有许多作者,并避免了has_and_belongs_to_many关系的混乱。
此外,如果你愿意,你几乎可以假装BookCharacter表不存在。您可以调用class Character < ActiveRecord::Base
has_many :book_characters
has_many :books, through: :book_characters
has_many :authors, through: :books
end
并且rails将为您创建中间对象。但是,BookCharacter模型在未来可能会证明非常有用。你永远不知道你何时想要区分第6册中的哈利波特和第7册中的哈利波特。