【问题标题】:How to define foreign key in Ruby on Rails如何在 Ruby on Rails 中定义外键
【发布时间】: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


【解决方案1】:

我不完全确定你在问什么,你看到了什么行为,或者你期望什么行为。也就是说,这就是您粘贴的代码所发生的情况(案例 2?):

trade = Trade.first
trade.isbn

这将返回Trade#isbn 引用的Book 实例。

trade.isbn.title

这相当于

book = trade.isbn
book.title

返回Trades#isbn 引用的Book 实例的标题。这不符合您的预期吗?

【讨论】:

  • 感谢您回答我的问题。我认为case1和case2是一样的。我想在案例 1 中访问书名
  • 我不确定您所说的“案例 1”是什么意思,抱歉。你可能会问trade.book.title
  • 是的,我想知道为什么 trade.book.title 不适用于案例 1
【解决方案2】:

所以你的问题是符号(:isbn)和字符串("isbn")有什么区别? 在镜头中,符号被认为是 Ruby 的不可变字符串,您可以在此处阅读更多内容:

http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/

一般的约定是在你传递给方法的选项哈希中使用符号作为键,尽管一些库/宝石等支持两者。但在 Yours 的特殊情况下,该值似乎被强制转换为字符串,因此作为选项传递给foreign_key 的所有内容都将使用to_s 转换为字符串。

【讨论】:

    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多