2013-03-03 64 views
0

我真的很陌生,所以我很抱歉如果我沒有考慮這個權利。我有一份報告,我需要能夠爲該報告分配多個用戶。用戶可以分配給多個報表,並且報表可以有多個用戶。如何在允許的情況下創建數據庫關係。我知道如何將一個用戶分配給一個報告,但不是多個用戶分配給一個報告。創建數據庫關係,允許同一個ID的多個任務

回答

2

我會使用一個連接類來實現這一目標:

class Report 

    has_many :assignments 
    has_many :users :through => :assignments 

end 

class User 

    has_many :assignments 
    has_many :reports, :through => :assignments 

end 

class Assignment 

    belongs_to :report 
    belongs_to :user 

end 

Assignment有兩個字段:report_iduser_id創建關係。

閱讀on Rails的指南的Ruby的Active Record協會:http://guides.rubyonrails.org/association_basics.html

+0

好吧,開始有意義,但我更清楚地理解它爲什麼我不會使用has_and_belongs_to_many作爲一個報告有許多用戶和用戶可以屬於許多報告?非常感謝幫忙。 – user2128197 2013-03-03 05:42:33

+0

您可以使用它,但使用上述功能,您可以獲得相同的功能,並且可以將字段添加到作業(如日期,備註等)中。 habtm隱藏了連接表。整體功能類似。 – 2013-03-03 05:50:05

0

我強烈建議你熟悉Ruby on Rails的指南。他們將被證明是一種無價的資產!對於這個任務該網站將是RailsGuides Active Record Associations

就代碼而言,您希望創建三個數據庫表:報告,reports_users和用戶,其中reports_users是一個連接表。

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string  :name,  :null => false  
     t.timestamps 
    end 
    end 
end 


class CreateReports < ActiveRecord::Migration 
    def change 
    create_table :reports do |t| 
     t.string  :name,  :null => false  
     t.timestamps 
    end 
    end 
end 


class ReportsUsers < ActiveRecord::Migration 
    def change 
    create_table :reports_users, :id => false do |t| 
     t.references :user,   :null => false        
     t.references :report,   :null => false        
    end 
    end 
end 

運行此遷移後,您需要在模型中設置活動記錄關聯。

class User < ActiveRecord::Base 
    has_and_belongs_to_many :reports 
end 

class Report < ActiveRecord::Base 
    has_and_belongs_to_many :user 
end 

這將設置數據庫和多對多模型連接。這會讓你開始。現在你必須去創建一些視圖

+0

作爲一個側面說明Rails指南網站是http://guides.rubyonrails.org/和另一個你應該熟悉自己的網站是rails api頁面http://api.rubyonrails.org/ – 2013-03-03 05:45:07

相關問題