我想知道...... (1)2个相同列的2个不同表的正确关联应该是什么 (2)如何在for循环
的视图中显示用户列表因此,一个表称为Attending,有2列:Events&用户 另一个表名为NotAttending,有2列:Events&用户
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 %>
谢谢!
答案 0 :(得分:1)
ASIDE:为什么不将Attending和Nonattending组合成一个包含三列,event,user和is_attending的表(如果参加则为true,如果不参加则为false)?
但无论如何,我们假设数据模型是固定的......
你不能两次使用has_many:users。你可以选择另一种方法:
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