2011-09-29 61 views
0

我在想... (1)对于2个同列的两个不同表应该如何正确关联 (2)如何在视图中显示用户列表与循环两列相同列的钢轨关联

所以一个表被称为参加并有2列:活动&用户 另一个表称为NotAttending并有2列:活动&用户

class User < ActiveRecord::Base 
    has_many :attending 
    has_many :notattending 
    has_many :events, :through => :attending 
    has_many :events, :through => :notattending 
end 

class Event < ActiveRecord::Base 
    has_many :attending 
    has_many :notattending 
    has_many :users, :through => :attending 
    has_many :users, :through => :notattending 
end 

class Attending < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :event 
end 

class Notattending < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :event 
end 

我怎么会显示用户的列表参加和没有在视图中插入图片?我得到错误undefined method users for nil:NilClass

<% for user in @attending.user %> 
    <%= user.name %></br> 
<% end %> 

谢谢!

回答

1

ASIDE:为什么不把参加和非参加组合成一个表,包含三列,事件,用户和is_attending(如果参加则为true,如果不参加则为false)?

但不管,让我们假设数据模型是固定的...

不能使用的has_many:用户的两倍。你可以选择另一种方法:

class User < ActiveRecord::Base 
    has_many :attending 
    has_many :notattending 
    def events 
    self.attending.map(&:events) + self.nonattending.map(&:events) 
    end 
end 

class Event < ActiveRecord::Base 
    has_many :attending 
    has_many :notattending 
    def users 
    self.attending.map(&:users) + self.nonattending.map(&:users) 
    end 
end 
+0

谢谢@Rob:你的解决方案组合成一张表更有效率! – Sayanee