首页 > 解决方案 > 在rails中两个或更多模型之间的索引处显示数据

问题描述

目前,我有两张桌子countriesusers

countries类似这样的模式,

对于users桌子,

因此,为了users/index.html.erb显示我从国家/地区表 id 获得的 Born_at_id 或 live_at_id,我想显示该国家/地区的名称。

我已经尝试搜索很多关于这个问题的文章,但没有一个对我有用。

对于我的表,我是否需要在迁移期间为 users 表添加引用,或者仅使用has_one, many 和 belongs_to 以及如何在索引中显示数据就足够了。

标签: ruby-on-railsrubypsql

解决方案


在您的模型中添加以下关联,

用户.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

推荐阅读