2013-02-14 116 views
1

我有兩個活動記錄模式現在,UserEvent 有許多事件中,用戶可以選擇感興趣的事件或決定參與該事件。2 ActiveRecord的模型關聯

如何編寫遷移和模型?

回答

0

由於Shweta建議,你需要一個多對多的關係。事實上,它看起來像你需要兩個,一個用於興趣,一個用於參與。最簡單的實現依賴於has_and_belongs_to_many:

用戶模型

has_and_belongs_to_many :interests, :class_name => Event, :join_table => "interests_users" 
has_and_belongs_to_many :participations, :class_name => Event, :join_table => "participations_users" 

事件模型

has_and_belongs_to_many :followers, :class_name => User, :join_table => "interests_users" 
has_and_belongs_to_many :participants, :class_name => User, :join_table => "participations_users" 

在你的連接表遷移:

def change 
    create_table :interests_users, :id => false do |t| 
    t.integer :event_id 
    t.integer :user_id 
    end 

    create_table :participations_users, :id => false do |t| 
    t.integer :event_id 
    t.integer :user_id 
    end 
end 

您應該能夠從這裏繼續

0

但誰創造這些事件? 我認爲這assosiation將是對你有好處:

models/event.rb 
    has_many :users, :dependent => :destroy 
models/user.rb 
    belongs_to :event 

而且用戶遷移應該看起來像這樣:

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :name 
     t.integer :event_id 

     t.timestamps 
    end 

    add_index :users, :event_id 
    end 
end 

事件遷移:

class CreateEvents < ActiveRecord::Migration 
    def change 
    create_table :events do |t| 
     t.string :name 

     t.timestamps 
    end 
    end 
end 

你可以閱讀有關軌道的詳細信息本指南中的聯想: http://guides.rubyonrails.org/association_basics.html

+0

我應該如何區分**在**和**參與者**之間進行交流? – 2013-02-14 09:06:27

0

用戶模式

has_many :events, :dependent => :destroy 

事件模型

belongs_to :user 

事件遷移:

class CreateEvents < ActiveRecord::Migration 
    def change 
    create_table :events do |t| 
     t.string  :name 
     t.references :user 
     t.boolean :participant, :default => true, :null => false # the user is participant by default set, default to true 
     t.timestamps 
    end 
    end 
end 
+0

我應該提到,用戶可以與事件沒有關係,不感興趣或參與者 – 2013-02-14 09:42:29

+0

是否像,用戶可以參與或對許多事件感興趣?那麼你需要用戶和事件之間的多對多關係 – shweta 2013-02-14 09:48:20