【问题标题】:grap user information from a group of participants从一组参与者中获取用户信息
【发布时间】:2022-06-12 14:07:02
【问题描述】:

用户有很多参与者。

架构

User model                      Participant model        dance
id                              id                        id                 
name                            user_id
email                           dance_id  
address

用户.rb

has_many :participants

参与者.rb

belongs_to :user
belongs_to :dance

舞蹈.rb

has_many :participant

我有一整天参加舞蹈的参与者的名单。 participants = dances.map(&:participant)

 [#<ActiveRecord::Associations::CollectionProxy [#<Participant id: 
  1, user_id: 1, dance_id: 1, created_at: "2022-06-02 05:08:04.249558000 +0000", 
  updated_at: "2022-06-02 05:08:04.249558000 +0000">]
    [......dances_2_participants......]
     [......dances_3_participants......]
        [......dances_4_participants......]

        >

从上面得到的结果。如何列出用户信息。例如用户(电子邮件,地址)

【问题讨论】:

    标签: ruby-on-rails activemodel


    【解决方案1】:

    您可以将这些关联添加到您的 Dance 模型中

    has_many :participants
    has_many :users, through: :participants
    
    class Dance < ApplicationRecord
      has_many :participants
      has_many :users, through: :participants
    end
    
    class Participant < ApplicationRecord
      belongs_to :user
      belongs_to :dance
    end
    
    class User < ApplicationRecord
      has_many :participants
    end
    
    

    接下来你可以做到dances.map(&amp;:users)

    但请记住,不仅可以有 uniq 记录。

    如果您的Dance 模型只能有一个参与者,那么可以这样做:

    class Dance < ApplicationRecord
      has_one :participant
      has_one :user, through: :participant
    end
    

    您的代码将是dances.map(&amp;:user)

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多