【问题标题】:Rails 3 : Cannot update join table records with has_many throughRails 3:无法通过 has_many 更新连接表记录
【发布时间】:2015-05-06 23:17:03
【问题描述】:

设置

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,但丢失或找不到丢失的信息。

使用导轨 3.2.21

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 给连接表一个主键对我来说似乎很奇怪,但正如你所建议的,这就是 rails 所要求的。
    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2016-01-07
    • 2015-03-23
    相关资源
    最近更新 更多