【问题标题】:My Through Table is Pulling the wrong Active Records Assocations我的直通表拉错了 Active Records 关联
【发布时间】:2017-01-31 15:04:43
【问题描述】:

我正在开发一个示例 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 调用,但我不确定如何配置它以提取用户关联的事件记录?

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

事件.rb

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

end

参加者.rb

class Attendee < ApplicationRecord
  belongs_to :event
  belongs_to :user
end

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

【问题讨论】:

  • has_many :events_to_attend, through: :attendees, source: :user 那是因为您告诉它获取用户:source: :user。试试source: :event 看看会发生什么:)
  • 啊。固定的!!谢谢

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


【解决方案1】:

你有...

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

我认为您想要的是事件,而不是用户...

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

【讨论】:

  • 做到了!谢谢你。由于某种原因(可能是我自己的错),昨晚没有奏效。
  • 很高兴我能帮上忙!如果您发现答案有用,请随时“接受”它(选项在我的答案左侧)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 2014-11-14
相关资源
最近更新 更多