2010-12-22 181 views
0

我在积极的轨道纪录协会新的,所以我不知道如何解决以下问题: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 

请,没有任何人有一个解决方案/提示如何解决这个轨道的方式?

回答

0

我对如何关联一个错误的认识模型工作。由于这个错误的观点,我的问题首先是错误的。

例如,我有一个模型会议会议,其中有许多模型参与者的参与者。我不知道我不仅可以检索meeting.participants,还可以通过participant.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这样的参与者模型。 有谁知道如何缩短这些嵌套的资源?

0

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

在与会者模式

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 
+0

感谢您的回答,但是我对模型关联有错误的理解。因此,我的问题首先是错误的。看我自己的解决方案我是如何解决问题的。 – 2010-12-24 11:40:07