[英]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: 我正在尝试使用Rails 3从头开始构建一个简单的项目。通常,这些模型如下:
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. 然后我们使用
award.id
和student.id
来获取相应的记录。
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. 在这种情况下,我们可以使用公司的符号(例如
MSFT
或GOOG
来标识公司,而不是使用company.id。 For example, in stock_quotes, we can store the symbol of the company directly instead of using company.id
. 例如,在stock_quotes中,我们可以直接存储公司的符号,而不必使用
company.id
。 In this case, is there a way to specify it in the models? 在这种情况下,是否可以在模型中指定它?
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many
Check out :primary_key and :foreign_key options 检出:primary_key和:foreign_key选项
In addition to Slawosz' answer, this question about non-integer primary keys is also relevant to your question. 除了Slawosz的回答, 这个问题对非整数主键也关系到你的问题。 IMHO, it would be easier to just use integer id's like in the example of
Award
and Student
. 恕我直言,像在
Award
和Student
的示例中那样使用整数id会更容易。
Slawosz has the answer right. Slawosz有答案的权利。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.