在 Ruby on Rails 中,模型如何“has_many”?和“属于”使用主 ID 以外的其他字段?
我正在尝试使用 Rails 3 从头开始构建一个简单的项目。通常,模型如下所示:
class Student < ActiveRecord::Base
has_many :awards
end
class Award < ActiveRecord::Base
belongs_to :student
end
并且我们使用 award.id
和 student.id
来获取相应的记录。
但如果是的话呢?
class Company < ActiveRecord::Base
has_many :stock_quotes
end
class StockQuote < ActiveRecord::Base
belong_to :company
end
在这种情况下,我们可以使用公司的符号,例如 MSFT
或 GOOG
来标识公司,而不是使用company.id。例如,在stock_quotes中,我们可以直接存储公司的代码,而不是使用company.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many
查看 :primary_key 和 :foreign_key 选项
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many
Check out :primary_key and :foreign_key options
除了 Slawosz 的回答之外,这个关于非整数主键的问题也与您的问题相关。恕我直言,仅使用整数 id 会更容易,例如
Award
和Student
的示例。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
andStudent
.Slawosz 的答案是正确的。详细一点(下次我搜索这个时)应该是这样的:
Slawosz has the answer right. To be verbose (and for the next time I search this) it should be like this: