試圖學習如何通過我正在使用的關聯正確導航has_many,並且我擊中了一堵磚牆。我已經在這裏抽象了這些類,以使它們更容易關聯。如何通過使用自定義鍵名稱的關聯來確定has_many的範圍?
一本書有很多字符。 一個角色有很多書。 是什麼使得它從一個典型的HMT協會不同的是,當一個字符用一本書相關的,它被添加無論是作爲一個「好人」或「壞傢伙」,例如:
book.bad_guys << character
我能夠提高book.good_guys的結果就好了。什麼引起了我的一個循環,無論何時我想以另一種方式走,找一個角色並找出他所關聯的書,它都會返回一個Book :: ActiveRecord_Associations_CollectionProxy而不是實際的結果列表。
如果我不character.books.first這是輸出(注意它是如何試圖找到一個「good_guy」屬性,而不是去休書和字符列是連接表的一部分)
Document Load (1.1ms) SELECT "books".* FROM "books" INNER JOIN "book_characters" ON "books"."id" = "book_characters"."good_guy" WHERE "book_characters"."character_id" = ? ORDER BY "books"."id" ASC LIMIT ? [["character_id", 1], ["LIMIT", 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: book_characters.good_guy: SELECT "books".* FROM "books" INNER JOIN "book_characters" ON "books"."id" = "book_characters"."good_guy" WHERE "book_characters"."character_id" = ? ORDER BY "books"."id" ASC LIMIT ?
from /home/linux/.rvm/gems/ruby-2.3.1/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize'
我懷疑我需要確定角色模型如何通過直通表進行搜索並最終到達書籍表,但我沒有取得任何成功。
是否可以在角色模型上添加一個作用域以修改它在通過表中的搜索方式?還是有什麼我需要做的,以找到相關的記錄?預先感謝您提供的任何幫助!
class Character < ApplicationRecord
has_many :book_characters
has_many :books, -> { where(book_characters: ("character = :character.id")) }, :through => :book_characters # I don't think my wording is correct here
class Book < ApplicationRecord
has_many :book_characters
has_many :good_guys, through: :book_characters, :source => "character"
has_many :bad_guys, through: :book_characters, :source => "character"
class BookCharacter < ApplicationRecord
belongs_to :character
belongs_to :book, :foreign_key => :bad_guy
belongs_to :book, :foreign_key => :good_guy
這裏是BookCharacters遷移...
class CreateBookCharacters < ActiveRecord::Migration[5.0]
def change
create_table :book_characters do |t|,
t.references :book, foreign_key: true
t.references :entity
只是爲了澄清一下,你希望能夠做一個像'character.books'這樣的查詢,並讓它返回一個顯示所有字符所在書籍的關係? – quicklikerabbit
@quicklikearabbit:是的,那就是我之後 – Spectator6