2012-01-17 107 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