Rails 3:无法通过 has_many 更新连接 table 记录

Rails 3 : Cannot update join table records with has_many through

设置

class ContactGroup < ActiveRecord::Base
  has_many :accounts_contact_groups
  has_many :accounts, through: :accounts_contact_groups
end

class AccountsContactGroup < ActiveRecord::Base # Join table
  belongs_to :account
  belongs_to :contact_group
end

class Account
  # nothing linking to above 
  # as I do not need a relationship from this direction
end

数据

> ContactGroup.all
=> [#<ContactGroup id: 7, position: nil, name: "General", fixed: true>]

> AccountsContactGroup.all
=> [#<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 0>,
    #<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 1>,
    #<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 2>]

查询

很好,因为连接中没有帐户 ID table

> ContactGroup.first.accounts
=> []
> ContactGroup.first.account_ids
=> []

我有我的加入记录

> ContactGroup.first.accounts_contact_groups
=> [#<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 0>,
    #<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 1>,
    #<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 2>]

那么为什么我不能更新加入 table 记录?

> acg = ContactGroup.first.accounts_contact_groups.first
=> #<AccountsContactGroup account_id: nil, contact_group_id: 7, position: 0>
> acg.account_id
=> nil
> acg.account_id = 1
=> 1
> acg.account_id
=> 1
> acg.save
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'accounts_contact_groups.' in 'where clause': UPDATE `accounts_contact_groups` SET `account_id` = 1 WHERE `accounts_contact_groups`.`` IS NULL
# or
> acg.update_attribute(:account_id, 1)
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'accounts_contact_groups.' in 'where clause': UPDATE `accounts_contact_groups` SET `account_id` = 1 WHERE `accounts_contact_groups`.`` IS NULL

可以看到报错信息,没有设置加入的字段名accounts_contact_groups

UPDATE `accounts_contact_groups` 
SET `account_id` = 1 
WHERE `accounts_contact_groups`.`` IS NULL

我不明白的是如何设置模型以使其正确设置。

我在关注 http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association,但要么错过了,要么找不到丢失的信息。

使用 rails 3.2.21

Rails 无法识别您的直通记录以更新它,因为它没有主键。给 accounts_contact_groups table 一个 id 字段,或者尝试 composite_primary_keys gem。