【发布时间】:2012-01-17 23:51:17
【问题描述】:
我是 Ruby on Rails 的新手,我正在拼命尝试让 HABTM 协会正常工作。我有一个客户数据库,其中每个客户都可以有很多联系人。从客户“显示”视图中,我希望有一个链接来向该选定客户添加新联系人。
到目前为止,我有以下数据:
models/customer.rb:
class Customer < ActiveRecord::Base
has_and_belongs_to_many :contacts
accepts_nested_attributes_for :contacts, :allow_destroy => true
end
models/contact.rb:
class Contact < ActiveRecord::Base
has_and_belongs_to_many :customers
end
views/customers/show.html.erb:
<%= link_to 'Add new contact', new_customer_contact_path(@customer) %>
我还有三张桌子:
customers (id, name)
contacts (id, name)
contacts_customers (contact_id, customer_id) <- the join-table
现在,当我点击“添加新联系人”链接时,我进入“新客户”页面,它甚至正确分配了 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
【问题讨论】:
标签: ruby-on-rails associations has-and-belongs-to-many