Rails - 一个 table 引用了另外两个 table

Rails - one table with references to two other tables

我为我的 Web 应用想出了这个 table 架构:

+----------+------------+------------+
| User     | Event      | Invitation |
+----------+------------+------------+
| id       | id         | id         |
+----------+------------+------------+
| email    | user_id    | user_id    |
+----------+------------+------------+
| password | start_time | event_id   |
+----------+------------+------------+
|          | end_time   | confirmed  |
+----------+------------+------------+

这是三个模型。用户可以有很多事件和很多邀请。活动属于一个用户,邀请属于一个用户和一个活动。

用户模型

class User < ActiveRecord::Base
  has_many :events
  has_many :invitations
end

用户迁移

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :password
      t.timestamps null: false
    end
  end
end

事件模型

class Event < ActiveRecord::Base
  belongs_to :user
end

事件迁移

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.references :user
      t.datetime :start
      t.datetime :end
      t.string :description
      t.string :venue

      t.timestamps null: false
    end
  end
end

邀请模型

class Invitation < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

邀请迁移

class AlterInvitation < ActiveRecord::Migration
  def change
    create_table :invitations do |t|
      t.references :event
      t.references :user
      t.boolean :confirmed
      t.timestamps null: false
    end
  end
end

现在这是我对 Rails 的理解,所以如果我想太聪明而不遵守约定,请告诉我,因为我确信这是非常标准的 schema/model设置。

例如,当我尝试这样做时:

u = User.first
u.events.create(start_time:DateTime.now, end_time:DateTime.now + 1)

一切如期进行。 user_id 分配给创建它的用户。现在假设我们有一个用户 u2 已发送邀请参加我刚刚在上面创建的活动 e1

e1 = u.events.first
u2.invitations.create(event_id:e1.id, confirmed:false)

当我想引用属于事件 e1 的邀请时,它并没有像我期望的那样工作:

e1.invitations

NoMethodError: undefined method `invitations' for #<Event:0x007ff214387a08>

我的印象是行 belongs_to :event 将为我启用方法 invitations。谁能帮我解决这个问题?谢谢。

尝试

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :invitations, through: :user
end

事件至少应该 has_many :invitations,如果我理解你的意图。

乍一看,我觉得 "u2" 正试图发送不属于她的活动邀请。它说事件属于一个用户我想也许你的意思是一个事件有很多用户,或者你的意思是一个事件可以属于很多用户?无论如何,我认为您的问题在于您的模型定义。我认为迁移并不重要,导致阅读混乱。

警告:我现在甚至不应该阅读这篇文章,所以这无论如何都不是一个全面的回应。