【发布时间】: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