在 rails 中显示两个或更多模型之间的索引处的数据
Display data at index between two models or more in rails
目前,我有两个 table countries
和 users
countries
的架构是这样的,
- id
- country_code
- 姓名
和 users
table,
- id
- 姓名
- born_country_id
- live_at_country_id
所以对于 users/index.html.erb
而不是显示我从国家 table id 获得的 born_at_id 或 live_at_id,我想显示那个国家的名称。
我已经尝试搜索了很多关于这个问题的文章,但是 none 对我有用。
对于我的table,我是否需要在用户table 的迁移过程中放置引用,或者仅使用has_one
、many 和belongs_to 是否足够以及如何显示索引中的数据。
在您的模型中添加以下关联,
user.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
country.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
目前,我有两个 table countries
和 users
countries
的架构是这样的,
- id
- country_code
- 姓名
和 users
table,
- id
- 姓名
- born_country_id
- live_at_country_id
所以对于 users/index.html.erb
而不是显示我从国家 table id 获得的 born_at_id 或 live_at_id,我想显示那个国家的名称。
我已经尝试搜索了很多关于这个问题的文章,但是 none 对我有用。
对于我的table,我是否需要在用户table 的迁移过程中放置引用,或者仅使用has_one
、many 和belongs_to 是否足够以及如何显示索引中的数据。
在您的模型中添加以下关联,
user.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
country.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