ruby-on-rails-3 - ruby Rails 3: 无法通过has_many更新联接表记录

  显示原文与译文双语对照的内容
150 3

设置

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

查询

很好,因为连接表中没有of的帐户

> 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

时间:原作者:0个回答

108 4

Rails 无法通过记录标识你的through,因为它没有主键。或者给 accounts_contact_groups 表一个id字段,或者尝试 composite_primary_keys gem 。

原作者:
...