2012-10-12 57 views
2

這裏第一個問題和Ruby的新問題,所以對我來說很簡單。在我開始確定我正在理解構建基本概念之前,我試圖爲我的第一個應用程序繪製一些模型+關聯。Rails newb - 你能幫我模型嗎?

enter image description here

是我的模型正確的我想要實現什麼? 如果不是,有人可以提供一些建議或建議嗎? 有沒有更簡單的方法來做我想做的事情? 從工作流的角度來看,這是一種讓初學者在缺乏實體語法的情況下開始使用的有效方式嗎?

謝謝!

+0

顧客:它有_many_ quote_requests,爲什麼你通過quote_request_id引用一個報價?同樣適用於提供者中的quote_id。我認爲你可以'看'它,因爲你有兩個兩個模型與參考兩個方向(customers/quote_requests)和(提供商/報價) – Nippey

+0

Nippey - 感謝您的反饋...我理解你的問題,但不相當知道如何回答它。 爲了代替客戶中的單數「quote_request_id」,我該如何改變它,或者如何顯示「許多」關聯? 從客戶/提供商模型中刪除「quote_request_id」和「quote_id」是否可以? – jawise

+0

那麼,如果我正確地理解了'quote_request_id'和'quote_id',那麼通過選擇具有右'customer_id'的表'quote_requests'來查找報價請求。那麼你不需要上面提到的id。 – Nippey

回答

0

試試這個

class User < ActiveRecord::Base 
    has_many :customers 
    has_many :providers 
end 

class Customer < ActiveRecord::Base 
    belongs_to :user 

    has_many :customer_quote_requests 
    has_many :quote_requests, :through => :customer_quote_requests 

    has_many :customer_quotes 
    has_many :quotes, :through => :customer_quotes 
end 

class Provider < ActiveRecord::Base 
    belongs_to :user 

    has_many :provider_quotes 
    has_many :quotes, :through => :provider_quotes 

    has_many :provider_quote_requests 
    has_many :quote_requests, :through => :provider_quote_requests 

end 

class QuoteRequest < ActiveRecord::Base 
    has_many :customer_quote_requests 
    has_many :customers :through => :customer_quote_requests 

    has_many :provider_quote_requests 
    has_many :providers, :through => :provider_quote_requests 
end 

class CustomerQuoteRequest < ActiveRecord::Base 
    belongs_to :customer 
    belongs_to :quote_request 
end 

class Quote < ActiveRecord::Base 
    has_many :provider_quotes 
    has_many :provider, :through => :provider_quotes 

    has_many :customer_quotes 
    has_many :customers, :through => :customer_quotes 

end 

class ProviderQuote < ActiveRecord::Base 
    belongs_to :provider 
    belongs_to :qoute 
end 

class ProviderQuoteRequests < ActiveRecord::Base 
    belongs_to :provider 
    belongs_to :quote_requests 
end 

class CustomerQuotes < ActiveRecord::Base 
    belongs_to :customer 
    belongs_to :quote 
end 
+0

Dipak - 謝謝! 如果你有另一個快速秒,你能分享爲什麼我在這裏使用「has_many_and_belongs_to」嗎?我猜你創建的其他模型滿足我的意圖,並使其不必要... – jawise

+0

超級尷尬,我得到的關聯語法錯誤...'has_and_belongs_to_many'是我的意思,而不是在我的腦海中翻轉它。 :o – jawise

+1

has_many - through比has_many_and_belongs_to更好,因爲看到這個鏈接 - (1)http://railscasts.com/episodes/47-two-many-to-many(2)http://blog.hasmanythrough.com/ 2007/1/15 /基本護欄關聯基數?utm_source =通過twitterfeed&utm_medium =微博 –

0

一般回答你的問題我下面的評論:

如果你有一個1:n關係的兩個表,你不引用所有n元素在你父表。您只能定義子表所屬的1

在你的情況: quote_requests屬於customers。 因此,您通過customer_id參考quote_requests內的客戶。

這就夠了。這樣,您可以擁有屬於客戶的零,一個或多個quote_requests。 (告訴自己:quote_request_id如果有零個或多個條目有什麼用處?如果將它設置爲零,那麼它是引用一個id還是意味着沒有元素被分配? )