我的 Through Table 提取了错误的 Active Records 关联

My Through Table is Pulling the wrong Active Records Assocations

我正在开发一个示例 Rails 应用程序,其中包含用户、事件(用户创建的),最终,用户将能够订阅/参加这些事件。

我需要创建一个通过 table 来跟踪这些事件的参与者的 event_ids 和 user_ids。虽然我认为它设置正确,但当我通过用户查询数据库时,我得到的不是事件 ActiveRecords,而是用户活动记录。

 testUser = User.find(4)
 testUser.events_to_attend
SELECT "users".* FROM "users" INNER JOIN "attendees" ON "users"."id" = "attendees"."user_id" WHERE "attendees"."user_id" = ?  [["user_id", 4]]

 => #<ActiveRecord::Associations::CollectionProxy [#<User id: 4, name: "Steve Bear", email: "steve@bear.com", password: nil, password_confirmation: nil, created_at: "2016-09-01 21:20:08", updated_at: "2016-09-01 21:20:08", password_digest: "a$iytkAI9EmrmCG6aRsvK13.50ssBxWs.i5G1T1HjgPQz...">, #<User id: 4, name: "Steve Bear", email: "steve@bear.com", password: nil, password_confirmation: nil, created_at: "2016-09-01 21:20:08", updated_at: "2016-09-01 21:20:08", password_digest: "a$iytkAI9EmrmCG6aRsvK13.50ssBxWs.i5G1T1HjgPQz...">]> 

从这里可以看出我没有进行正确的 SQL 调用,但我不确定如何配置它以提取与用户关联的事件记录?

user.rb

class User < ApplicationRecord
  has_many :events, dependent: :destroy
  has_many :attendees
  has_many :events_to_attend, through: :attendees, source: :user

  validates :name, presence: true, length: { maximum: 50 }

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: {maximum: 225}, format: {:with => VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false }

  has_secure_password
  validates :password, length: { minimum: 6 }, presence: true, allow_nil: true
end

event.rb

class Event < ApplicationRecord
  belongs_to :user
  validates :user_id, presence: true

end

attendee.rb

class Attendee < ApplicationRecord
  belongs_to :event
  belongs_to :user
end

如果对任何人有帮助,我很乐意列出我的迁移

你有...

  has_many :events_to_attend, through: :attendees, source: :user

我想你想要的是事件,而不是用户...

  has_many :events_to_attend, through: :attendees, source: :event