2012-01-17 66 views
2

我是Ruby on Rails的新手,我拼命嘗試獲取HABTM關聯。我有一個客戶數據庫,其中每個客戶可以有很多聯繫人。從客戶「展示」的角度來看,我希望有一個鏈接可以爲該客戶添加一個新的聯繫人。Ruby on Rails 3:HABTM關聯不更新連接表

到目前爲止,我有以下數據:

型號/ customer.rb:

class Customer < ActiveRecord::Base 
    has_and_belongs_to_many :contacts 
    accepts_nested_attributes_for :contacts, :allow_destroy => true 
end 

型號/ contact.rb:

class Contact < ActiveRecord::Base 
    has_and_belongs_to_many :customers 
end 

的意見/客戶/ show.html .erb:

<%= link_to 'Add new contact', new_customer_contact_path(@customer) %> 

我也ha已經三個表:

customers (id, name) 
contacts (id, name) 
contacts_customers (contact_id, customer_id) <- the join-table 

現在,當我點擊「添加新聯繫人」 -link,我得到一個「新客戶」頁面,甚至正確地分配CUSTOMER_ID,但是當我點擊「保存」填寫聯繫人信息後,聯繫人被創建,但聯接表(contacts_customers)未更新。因此,新創建的聯繫人不與客戶「連接」。

我已經瀏覽了這個網上約兩個小時,並不能幫助自己。如果有人能指引我正確的方向,我會非常高興!

謝謝!

[編輯:更新詳情] 這裏的哪個參數獲得經過一次我點擊「新建聯繫人」聯繫我「show.html.erb」視圖

Started GET "/customers/260/contacts/new" for 127.0.0.1 at 2012-01-18 08:21:28 
    Processing by ContactsController#new as HTML 
    Parameters: {"customer_id"=>"260"} 
    Customer Load (0.0ms) SELECT 'customers'.* FROM 'customers' WHERE 'customers'.'id' = 260 LIMIT 1 
    Rendered contacts/_form.html.erb (9.0ms) 
    Rendered contacts/new.html within layouts/application (13.0ms) 
    Completed 200 OK in 343 ms (Views: 26.0ms | ActiveRecord: 299.0ms) 

正如你所看到的, customer_id(我的例子中爲260)應該被傳遞給新的聯繫人控制器。 當我點擊「保存」,然而這將啓動POST請求實際創建數據庫條目,在CUSTOMER_ID 丟失僅接觸表被更新:

Started POST "/contacts" for 127.0.0.1 at 2012-01-18 08:28:00 +0100 
    Processing by ContactsController#create as HTML 
    Parameters: {"utf8"=>"Ô£ô", "authenticity_token"=>"jWMlruMezFGOy1j7vTbE9OcL8VareGUXS1AprBpNhGA=", "contact"=>{"anrede"=>"", "name"=>"Test", "position"=>"", "telefon"=>"", "mobil"=>"", "fax"=>"", "email"=>"", "sonstiges"=>""}, "commit"=>"Create Contact"} 
    BEGIN SQL (0.0ms) 
    INSERT INTO `contacts` (`anrede`, `email`, `fax`, `mobil`, `name`, `position`, `sonstiges`, `telefon`) VALUES ('', '', '', '', 'Test', '', '', '') (113.0ms) 
    COMMIT 
    Redirected to http://localhost:3000/contacts/626 
    Completed 302 Found in 174ms 

我不知道,如果是的任何幫助,但以防萬一。我的路線如下設置:

resources :contacts 
resources :customers do 
    resources :contacts 
end 

回答

2

要檢查的一件事是如果您使用宏attr_accessible定義任何屬性。欲瞭解更多信息,請看下面的鏈接。

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#label-Saving

我會建議測試控制檯中的參數散列。您可以使用記錄器語句來查看params散列並嘗試更改散列以使其工作。

這將是有益的,如果你發佈params散列,看看你缺少什麼

+0

非常感謝您的回覆!我已經嘗試瞭解我的參數哈希值並更新了我的問題。看來,在聯繫人/新表單和實際的POST請求之間的某處,customer_id會丟失。 – Weaz 2012-01-18 07:38:04

+0

您需要在新窗體中添加customer_id作爲隱藏字段。像這樣<%= hidden_​​field_tag(「customer_id」,@customer_id)%> – naren 2012-01-18 18:19:24

+0

使用<%= hidden_​​field_tag(「customer_id」,params [:customer_id]%>我設法將customer_id字段轉換爲新的POST請求。但是,連接表仍然不會被rails自動更新,我已經在考慮通過SQL查詢來手動執行它,因爲我無法得到它的工作:-(我幾乎可以肯定,有什麼問題我的控制器/模型設置的方式,我只是不能把它的手指上。可能有其他想法? – Weaz 2012-01-18 18:51:44