I am trying to update a cross-reference table in a database when the
user submits a simple form. The table has three columns, ‘id’,
‘location_id’ and ‘user_id’.
Using this action, I get no errors, but nothing happens to the table:
if @locationusers.update_attributes(:user_id => @user.id,
:location_id => @locations.map(&:id)
But what you probably want is a :has_many :through association table. Off the
top of my head:
[snip]
If there will never be any values in the cross-reference (AKA join)
table,
i.e., just the three columns mentioned, the conceptually simpler
has_and_belongs_to_many relationship works. IIRC, the join table should
be
named LocationsUsers. There is a way to override the join table name,
perhaps
through:
Class User < ActiveRecord::Base
has_and_belongs_to_many :locations, :through => :location_users
end
Class Location < ActiveRecord::Base
has_many :location_users
has_many :users, :through => :location_users
end
The update code is the same. Oh, and the class names in the previous
example
should be singular.
Thank you for your assistance Jeffrey. Your comments have helped.
When I try to do:
def update @user = User.find(params[:id]) @locations = Location.find(:all) @locations.each {|l| @user.locations << l}
end
I see this error:
“TypeError in UserController#updateLocation
can’t convert Location into Integer”
When I do: @locationsusers = LocationsUser.find(params[:id])
if @locationsusers.update_attributes(:user_id => @user.id, :location_id
=> @locations.map(&:id))
I don’t see any errors, but nothing changes in the database table.
Is there something else I’m missing?
if @locationusers.update_attributes(:user_id => @user.id,
:location_id => @locations.map(&:id)
But what you probably want is a :has_many :through association table. Off the
top of my head:
[snip]
If there will never be any values in the cross-reference (AKA join)
table,
i.e., just the three columns mentioned, the conceptually simpler
has_and_belongs_to_many relationship works. IIRC, the join table should
be
named LocationsUsers. There is a way to override the join table name,
perhaps
through:
Class User < ActiveRecord::Base
has_and_belongs_to_many :locations, :through => :location_users
end
Class Location < ActiveRecord::Base
has_many :location_users
has_many :users, :through => :location_users
end
The update code is the same. Oh, and the class names in the previous
example
should be singular.