简体   繁体   English

在Ruby on Rails中,模型“ has_many”和“ belong_to”如何使用除主ID之外的其他字段?

[英]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.idstudent.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. 在这种情况下,我们可以使用公司的符号(例如MSFTGOOG来标识公司,而不是使用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? 在这种情况下,是否可以在模型中指定它?

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 . 恕我直言,像在AwardStudent的示例中那样使用整数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.

相关问题 Rails has_many / belong_to协会 - Rails has_many/belong_to Associations 在rails中的has_many中的关联 - Associations in has_many , belong_to in rails 创建一个新对象时,不能使用Emirates_to / has_many关系设置user_id字段 - Can't set user_id field when creating a new object, using a belong_to / has_many relationship 如何在ruby中为用户和任务模型之间的has_many,belong_to关联创建迁移脚本 - How to create migration script for has_many, belong_to association between user and task model in ruby 如何使用联接表在Rails中创建has_many和belong_to一个关联? - How to create has_many and belong_to one associations in Rails using a join table? Rails为多个主键在belong_to和has_many之间设置了基于角色的关系 - Rails set role based relationship between belong_to and has_many for multiple primary keys Rails belongs_to has_many具有自定义外键 - Rails belong_to has_many with a custom foreign key 如何创建和保存具有has_many / belong_to关联的模型 - How to create and save an model that has a has_many/ belong_to association 我怎样才能使用户具有has_many个对象,但每个对象都可以属于许多用户? - How can I make a user has_many objects but each object can belong_to MANY users? Rails 4:子模型可以属于两个不同的父模型吗? - Rails 4: can a child model belong_to two different parent models
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM