Rails——一个表引用了另外两个表



我为我的web应用程序提出了这个表模式:

+----------+------------+------------+
| 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的理解,所以如果我太聪明了,不遵守惯例,请告诉我,因为我确信这是非常标准的模式/模型设置。

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

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"似乎是在试图发送一个不属于她的活动邀请。它说事件属于一个用户,我想你的意思可能是一个事件有很多用户,或者你的意思是一个活动可以属于很多用户?无论如何,我认为你的问题在于你的模型定义。我认为迁移并不重要,这会导致阅读混乱。

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

最新更新