【发布时间】: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