【问题标题】:Display data at index between two models or more in rails在rails中两个或更多模型之间的索引处显示数据
【发布时间】:2019-02-22 07:36:09
【问题描述】:

目前,我有两个表countriesusers

countries 类似这样的架构,

  • 身份证
  • 国家代码
  • 姓名

对于users 表,

  • 身份证
  • 姓名
  • born_country_id
  • live_at_country_id

所以对于users/index.html.erb,而不是显示我从国家/地区表 id 获得的 Born_at_id 或 live_at_id,我想显示该国家/地区的名称。

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

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

【问题讨论】:

    标签: ruby-on-rails ruby psql


    【解决方案1】:

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

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

    【讨论】:

    • 首先感谢您的快速响应,目前为 index.html.erb .. 如何获取数据?
    • 具有我定义的关联并通过index 操作传递User.includes(:born_country, :lived_at_country)。您可以在索引页面中获取&lt;%= user.born_at_country_name
    • 未定义方法“委托”,我需要什么吗?
    • @DanielSufian 使用delegate
    • @DanielSufian 你一定要详细阅读ActiveRecord Association & Rails Delegate 并在日常生活中练习
    猜你喜欢
    • 2019-05-14
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2014-01-13
    相关资源
    最近更新 更多