【问题标题】:Rails - one table with references to two other tablesRails - 一张表引用了另外两张表
【发布时间】:2015-11-14 05:35:09
【问题描述】:

我已经为我的网络应用提出了这个表架构:

+----------+------------+------------+
| 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。谁能帮我解决这个问题?谢谢。

【问题讨论】:

    标签: ruby-on-rails rails-migrations


    【解决方案1】:

    试试

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

    【讨论】:

    • 哦,我明白了 :) 这个成功了,而且正是我需要它做的事情。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2016-11-18
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多