views:

40

answers:

3

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?

+1  A: 

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.

captaintokyo
A: 

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
Bryce
are you sure? It seems that both of them need to be `:primary_key => :symbol, :foreign_key => :symbol`
動靜能量
I'm not totally sure on that (it's definitely untested) but it works the same way as if StockQuote had a column :company_id . Rails would automatically pick up on the foreign key (company_id) to Company and then use the PK :id to do the join. This is overriding each other. If anything, I may have them reversed.
Bryce