My Through Table正在拉错错误的Active Records协会

时间:2016-09-22 21:28:06

标签: sql ruby-on-rails ruby has-many-through

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

我需要创建一个直通表来跟踪这些事件的与会者的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: "$2a$10$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: "$2a$10$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

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

1 个答案:

答案 0 :(得分:0)

你有......

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

我认为你想要的是活动,而不是用户......

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