рельсы ассоциаций для 2 таблиц с одинаковыми столбцами - PullRequest
0 голосов
/ 29 сентября 2011

Мне интересно ... (1) какие должны быть правильные ассоциации для 2 разных таблиц и с 2 одинаковыми столбцами (2) как отобразить список пользователей в представлениях с циклом for

одна таблица называется Attending и имеет 2 столбца: События и пользователи. Другая таблица называется NotAttending и имеет 2 столбца: Events & Users

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 Ответ

1 голос
/ 29 сентября 2011

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 
...