多个has_many通过关系无法正常工作

时间:2016-01-31 06:44:58

标签: ruby-on-rails ruby-on-rails-4

我正在为参与者创建一个考勤模块。当团队选择他们的事件时,值将存储在选择表中。

team.rb:

class Team < ActiveRecord::Base
  has_many :team_details
  has_many :participants, through: :team_details

  has_many :selections
  has_many :events,through: :selections
end

team_detail.rb:

class TeamDetail < ActiveRecord::Base
  belongs_to :team
  belongs_to :participant
end

event.rb:

class Event < ActiveRecord::Base
  has_many :selections
  has_many :teams,through: :selections
end

selection.rb:

class Selection < ActiveRecord::Base
  belongs_to :team
  belongs_to :event
end

但是当我通过has_many通过关系添加考勤模型时,我可以根据参与的事件标记每个团队的出勤率,这些值被存储在考勤表中,而不是存储在选择和考勤表中。

以下是添加考勤模型后的代码:

Event.rb:

class Event < ActiveRecord::Base
  has_many :selections
  has_many :teams,through: :selections

  has_many :attendances
  has_many :teams, through: :attendances
end

attendance.rb:

class Attendance < ActiveRecord::Base
  belongs_to :team
  belongs_to :event
end

team.rb:

class Team < ActiveRecord::Base
  has_many :team_details
  has_many :participants, through: :team_details

  has_many :selections
  has_many :events,through: :selections

  has_many :attendances
  has_many :events, through: :attendances
end

有什么问题?你能建议我解决这个问题吗?

我希望考勤表作为独立的active_record。

1 个答案:

答案 0 :(得分:0)

主要问题如下:

has_many :selections
has_many :events, through: :selections

has_many :attendances
has_many :events, through: :attendances

has_many关联创建一个实例方法,该方法使用数据库中的集合数据ActiveRecord填充。每个class只能有一个实例方法...因此关联将包含内部selectionsattendances数据的事件。< / p>

如果您有两个具有完全相同数据的连接表,则可以重命名关联,以便它们不会调用相同的实例方法:

has_many :selections
has_many :selection_events, through: :selections, class_name: "Event", foreign_key: :event_id

has_many :attendances
has_many :attendance_events, through: :attendances, class_name: "Event", foreign_key: :event_id

或者,如果你想拥有events,那么你最好创建自己的实例方法,结合两组数据:

#app/models/team.rb
class Team < ActiveRecord::Base
    has_many :selections
    has_many :selection_events, through: :selections, class_name: "Event", foreign_key: :event_id

    has_many :attendances
    has_many :attendance_events, through: :attendances, class_name: "Event", foreign_key: :event_id

    def events
       attendance_events + selection_events
    end
end

Ref

-

最终,如果您使用两个不同的联接表引用相同的数据,则表明您的应用程序结构存在重大问题。