Ian Vaughan
Ian Vaughan

Reputation: 21451

Rails 3 : Cannot update join table records with has_many through

Setup

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

Data

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

Queries

All good, as there are no account id's in the join table

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

And I have my join records present

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

So why can I not update the join table records?

> 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

I can see the error message, there is no field name set to join accounts_contact_groups

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

What I don't understand is how to setup the models so that it does set it correctly.

I was following http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association, but either missed or could not find the missing piece of information.

Using rails 3.2.21

Upvotes: 1

Views: 429

Answers (1)

boffbowsh
boffbowsh

Reputation: 106

Rails can't identify your through record to update it as it has no primary key. Either give the accounts_contact_groups table an id field, or try the composite_primary_keys gem.

Upvotes: 2

Related Questions