我正在關注http://railscasts.com/episodes/102-auto-complete-associationRails 3 find_or_create_by
一切似乎都很好。我試圖創建一個發票,也是一個客戶。它確實有效。一切都很酷。
客戶belongs_to的佔 發票belongs_to的帳戶 發票belongs_to的客戶
Buuut,這兩種模式(客戶端和發票),有一個必備屬性:ACCOUNT_ID。
當我試圖動態創建我得到一個錯誤:client_id: - can't be blank
的原因,我得到這個錯誤是因爲客戶端無法創建,因爲它需要在一個ACCOUNT_ID新客戶客戶端模型。如果我在客戶端模式刪除此行validates :account_id, :presence => true
發票加,但客戶沒有ACCOUNT_ID。
我確實有這clients_controller.rb在創建行動設置的默認值@client.account_id = current_user.account_id
invoice.rb
validates :account_id, :presence => true
validates :client_id, :presence => true
def client_name
client.name if client
end
def client_name=(name)
self.client = Client.find_or_create_by_name(name) unless name.blank?
end
該帳戶已創建。登錄的用戶已經有一個ACCOUNT_ID,可以這樣'current_user.account_id'進行訪問。問題在於將相同的account_id放入新的客戶記錄中。我現在就玩你的代碼。 – leonel
我有這個在我的發票模型'高清ORGANIZATION_NAME =(名稱); self.organization = Organization.find_or_create_by_name(name);除非name.blank? end'無法在模型中訪問current_user。 – leonel
如果您從帳戶記錄開始創建新的客戶記錄,那麼它將繼承它的account_id ...參見上文。 – Tilo