我正在研究一個具有用戶,事件(用戶創建)的示例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: "[email protected]", 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: "[email protected]", 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+\-.][email protected][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,通過:與會者來源:user'那是因爲你告訴它來抓取用戶:'source::user'。嘗試'源::事件',看看會發生什麼:) –
啊。固定!!謝謝 – got2jam