【发布时间】:2013-10-14 09:58:26
【问题描述】:
我正在使用 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
【问题讨论】:
-
你的问题到底是什么?
-
我想知道两个定义的区别。
-
请帮助我们帮助您;编辑您的问题以仅包含相关代码、您实际运行的“不起作用”的代码、它如何不起作用的具体解释、您获得的实际输出示例和您期望的输出。
标签: ruby-on-rails ruby ruby-on-rails-3 database-schema