【问题标题】:Rails model association problemRails 模型关联问题
【发布时间】:2010-12-22 23:52:24
【问题描述】:

我是 Rails 中活动记录关联的新手,所以我不知道如何解决以下问题:

我有一个名为“会议”和“用户”的表。我通过制作一个表“参与者”正确地将这两者关联在一起并设置了以下关联语句:

class Meeting < ActiveRecord::Base
    has_many :participants, :dependent => :destroy
    has_many :users, :through => :participants

class Participant < ActiveRecord::Base
    belongs_to :meeting
    belongs_to :user

最后一个模型

class User < ActiveRecord::Base
    has_many :participants, :dependent => :destroy

此时一切顺利,我可以通过在普通会议>show.html.erb 视图中调用@meeting.users 来访问特定会议的参加者的用户值。

现在我想在这些参与者之间建立联系。因此,我制作了一个名为“connections”的模型并创建了“meeting_id”、“user_id”和“connected_user_id”列。所以这些联系有点像某个会议中的友谊。

我的问题是:如何设置模型关联,以便轻松控制这些连接?

我想看看我可以使用的解决方案

@meeting.users.each do |user|
    user.connections.each do |c|
        <do something>
    end
end

我通过将会议模型更改为以下方式进行了尝试:

class Meeting < ActiveRecord::Base
    has_many :participants, :dependent => :destroy
    has_many :users, :through => :participants
    has_many :connections, :dependent => :destroy
    has_many :participating_user_connections, :through => :connections, :source => :user

请问,有没有人有解决方案/提示如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails activerecord join associations


    【解决方案1】:

    我对您的问题的理解是,您希望在参加同一会议的用户之间建立联系。也许这会奏效。

    在参与者模型中

     has_many => :connections
     has_many => :users, :through => :connections
    

    在用户模型中

    has_many => :connections
    

    那我想你可以这样做:

    @meeting.users.each do |user|
        user.connections.each do |c|
            #access each user object through the object |c|
        end
    end
    

    【讨论】:

    • 感谢您的回答,但是我对模型关联的理解有误。因此,我的问题一开始就错了。查看我自己的解决方案我是如何解决问题的。
    【解决方案2】:

    我对模型中的关联如何工作有错误的理解。由于这种错误的观点,我的问题一开始就错了。

    例如,我有一个模型会议 Meetings,其中有许多来自模型参与者的参与者。我不知道我不仅可以检索 meeting.participants,而且还可以通过参与者.meeting 访问分配给参与者的会议。

    所以我只是简单地将表参与者的user_id 和connected_user_id 列更改为participant_id 和connected_pa​​rticipant_id。然后在我做的模型中。

    模型参与者:

    class Participant < ActiveRecord::Base
        belongs_to :meeting
        belongs_to :user
        belongs_to :participating_user, :class_name => 'User', :foreign_key =>'user_id'
        has_many :connections 
    

    模型连接:

    class Connection < ActiveRecord::Base
        belongs_to :participant, :foreign_key => 'connected_participant_id'
    

    通过这些关联,我可以使用以下方法简单地访问视图中相应参与者的连接:

    查看(haml代码)

    - @meeting.participants.each do |p|
        %p
            %b Participant:
            = "#{p.user.first_name} #{p.user.last_name}"
        - p.connections.each do |c|
            %p
            %b Participant:
            = "#{c.participant.user.first_name} #{c.participant.user.last_name}"
    

    最后一点,c.participant.user.firstname 的这些嵌套资源很长。我更喜欢看到类似 p.connected_pa​​rticipants 的东西来解决 Participant 模型。 有谁知道如何缩短这些嵌套资源?

    【讨论】:

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