简体   繁体   中英

In Ruby on Rails, how can a model “has_many” and “belong_to” using a different field other than primary ID?

I am trying building a simple project from scratch using Rails 3. Usually, the models are like:

class Student < ActiveRecord::Base
  has_many :awards
end

class Award < ActiveRecord::Base
  belongs_to :student
end

and we use the award.id and student.id to get the corresponding records.

But what if it is

class Company < ActiveRecord::Base
  has_many :stock_quotes
end


class StockQuote < ActiveRecord::Base
  belong_to :company
end

In this case, we can use the symbol of the company, such as MSFT or GOOG to identify the company, instead of using the company.id. For example, in stock_quotes, we can store the symbol of the company directly instead of using company.id . In this case, is there a way to specify it in the models?

In addition to Slawosz' answer, this question about non-integer primary keys is also relevant to your question. IMHO, it would be easier to just use integer id's like in the example of Award and Student .

Slawosz has the answer right. To be verbose (and for the next time I search this) it should be like this:

#company
has_many :stock_quotes, :primary_key => :symbol

#stock_quote
belongs_to :company, :foreign_key => :symbol

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