简体   繁体   中英

How to define foreign key in Ruby on Rails

I'm using of Ruby on Rails.

I have some questions about definition of foreign key.

I defined some models.

When I access book title from class Trade via ISBN like this.

trade = Trade.first
trade.isbn #=> just get isbn in case 1.
trade.isbn.title #=> get book title in case 2.

Why case 2 doesn't work as expected??

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

I am not entirely sure what you're asking, what behavior you're seeing, or what behavior you expected. That said, this is what's happening with the code you've pasted (case 2?):

trade = Trade.first
trade.isbn

This returns the Book instance referenced by Trade#isbn .

trade.isbn.title

This is equivalent to

book = trade.isbn
book.title

which returns the title of the Book instance referenced by Trades#isbn . Is this not what you expected?

So Your question is what is difference between symbol ( :isbn ) and string ( "isbn" )? In shot symbols are considered Rubys immutable strings You can read more here:

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

In general convention is to use symbols as keys inside You options hashes that You pass to methods, though some libs/gems etc support both. But in particular case of Yours it looks like that this value is being typecasted to string, so everything that is passed as option to foreign_key will converted to string using to_s .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM