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://ift.tt/1nzY52u, but either missed or could not find the missing piece of information.
Using rails 3.2.21
Aucun commentaire:
Enregistrer un commentaire