我想出这个表架构我的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
对我来说。任何人都可以帮我解决这个问题吗?谢谢。
哦,我看到:)这一个做了伎俩,并做到了我需要它做的。 – user3056783