2015-11-13 18 views
0

我想出这个表架构我的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对我来说。任何人都可以帮我解决这个问题吗?谢谢。

回答

1

尝试

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

哦,我看到:)这一个做了伎俩,并做到了我需要它做的。 – user3056783

0

活动应has_many :invitations至少,如果我理解你的意图。

在我看来,乍一看,“U2”试图向不属于她的事件发出邀请。它说事件属于用户,我认为你的意思是说一个事件有很多用户,或者你的意思是一个事件可能属于许多用户?无论如何,我认为你的问题在于你的模型定义。我不认为迁移很重要,会造成杂乱的阅读。

警告:我现在甚至不应该读这个,所以这不是一个全面的回应。