我为我的网络应用程序设计了这个表架构:
+----------+------------+------------+
| 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
关于ruby-on-rails - Rails - 一张表引用了另外两张表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701979/