Ruby on Rails를 사용하고 있습니다.Ruby on Rails에서 외래 키를 정의하는 방법
외래 키의 정의에 대해 몇 가지 질문이 있습니다.
일부 모델을 정의했습니다.
ISBN을 통해 Trade 클래스에서 책 제목에 액세스 할 때.
trade = Trade.first
trade.isbn #=> just get isbn in case 1.
trade.isbn.title #=> get book title in case 2.
왜 2가 예상대로 작동하지 않습니까 ??
class Trade < ActiveRecord::Base
attr_accessible :cost, :isbn, :shop_id, :volume
# belongs_to :book, foreign_key: "isbn" # case 1
belongs_to :isbn, class_name: :Book, foreign_key: :isbn # case 2
belongs_to :shop
end
class Author < ActiveRecord::Base
attr_accessible :age, :name
has_many :books
has_many :trades, through
end
class Book < ActiveRecord::Base
self.primary_key = :isbn
attr_accessible :author_id, :cost, :isbn, :publish_date, :title
belongs_to :author
end
class Shop < ActiveRecord::Base
attr_accessible :name
has_many :trades
end
귀하의 궁금한 점은 무엇입니까? –
두 정의의 차이점을 알고 싶습니다. –
도와주세요. 관련 코드 만 포함하도록 질문을 편집하십시오. 실제로 실행중인 코드는 "작동하지 않습니다", 작동하지 않는 방법에 대한 구체적인 설명, 얻은 실제 출력 샘플 및 예상 한 출력을 포함해야합니다. –