ruby-on-rails - 在rails中两个或更多模型之间的索引处显示数据
问题描述
目前,我有两张桌子countries
和users
countries
类似这样的模式,
- ID
- 国家代码
- 姓名
对于users
桌子,
- ID
- 姓名
- Born_country_id
- live_at_country_id
因此,为了users/index.html.erb
显示我从国家/地区表 id 获得的 Born_at_id 或 live_at_id,我想显示该国家/地区的名称。
我已经尝试搜索很多关于这个问题的文章,但没有一个对我有用。
对于我的表,我是否需要在迁移期间为 users 表添加引用,或者仅使用has_one
, many 和 belongs_to 以及如何在索引中显示数据就足够了。
解决方案
在您的模型中添加以下关联,
用户.rb
class User < ActiveRecord::Base
belongs_to :born_country, foreign_key: :born_country_id, class_name: 'Country'
belongs_to :live_at_country, foreign_key: :live_at_country_id, class_name: 'Country'
delegate :name, to: :born_country, prefix: true
delegate :name, to: :lived_at_country, prefix: true
end
国家.rb
class Country < ActiveRecord::Base
has_many :born_users, foreign_key: :born_country_id, class_name: 'User'
has_many :live_at_users, foreign_key: :live_at_country_id, class_name: 'User'
end
您可以通过以下方式检查它,
@users = User.includes(:born_country, :lived_at_country).each do |user|
puts user.born_at_country_name
puts user.lived_at_country_name
end
推荐阅读
- c# - 当我从 AWS 迁移到 Azure DataLake 时如何避免存储此文件?
- jenkins - Jenkins:云或 AMI 实例上限将超出:
- photoshop - 用于更改文本编号并使用变量保存的 Photoshop 操作
- hyperledger-fabric - 超级账本作曲家中的 SKIP 和 LIMIT 运算符不起作用
- node.js - nodejs napi 模块没有自行注册
- surveymonkey - 如何使用调查猴子 API 发布多个调查回复
- c - C:对“xxx”函数的未定义引用
- airflow - 由于kombu中的更新而导致气流工作人员中断 - 异步错误
- kubernetes - 设置 ClusterIp 时不暴露 Kubernetes 服务
- amazon-web-services - 生成策略和签名值以将数据直接从 HTML 发布请求存储到 Amazon S3 存储桶