Rails 3:无法使用has_many更新连接表记录

时间:2015-03-05 14:35:15

标签: ruby ruby-on-rails-3 join has-many-through has-many

设置

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

> 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>]

那为什么我不能更新连接表记录?

> 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

1 个答案:

答案 0 :(得分:2)

Rails无法识别您的直通记录以更新它,因为它没有主键。要么为accounts_contact_groups表提供一个id字段,要么尝试composite_primary_keys gem。