Ruby on Rails 3:HABTM关联不更新join-table

时间:2012-01-17 23:51:18

标签: ruby-on-rails associations has-and-belongs-to-many

我是Ruby on Rails的新手,我正在拼命想让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) %>

我还有三张桌子:

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

1 个答案:

答案 0 :(得分:2)

要检查的一件事是你是否使用宏attr_accessible定义了任何属性。有关详细信息,请查看以下链接。

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

我建议在控制台中测试params hash。您可以使用logger语句查看params哈希值,并尝试更改哈希值以使其正常工作。

如果您发布params哈希以查看缺少的内容

,将会很有帮助