Rails模型关联问题

时间:2010-12-22 23:52:24

标签: ruby-on-rails activerecord join associations

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

我有一个名为'meeting'和'users'的表。通过创建表'参与者'并设置以下关联语句,我已正确地将这两者联系在一起:

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

此时一切顺利,我可以通过在普通会议&gt; 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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

所以我只是简单地将表参与者的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这样的东西来解决参与者模型。 有谁知道如何缩短这些嵌套资源?

相关问题