I had the same problem. I extended HasAndBelongsToManyAssociation to add the
functionality I needed. Here''s the code I ended up writing:
module ActiveRecord
module Associations
class HasAndBelongsToManyAssociation
def update_attributes(record, join_attributes = {})
#MES- Conver the record to an ID- if it''s ALREADY an ID, don''t
convert
record = record.id <http://record.id> if record.is_a? ActiveRecord::Base
#MES- Break the join_attributes into columns and values for those columns
cols_and_vals = join_attributes.to_a.transpose
#MES- Join the columns together with '' = ?, '', so the result
for [a, b]
# would be ''a = ?, b'' NOTE: We will have to add a trailing
'' = ?''
# in the SQL
col_string = cols_and_vals[0].join('' = ?, '')
#MES- Do the SQL, passing in the args
@owner.connection().update(sanitize_sql(["UPDATE #{@join_table} SET
#{col_string} = ? WHERE #{@association_class_primary_key_name} = ? AND
#{@association_foreign_key} = ?", cols_and_vals[1],
@owner.id<http://owner.id>,
record].flatten), "Update Attributes")
end
end
end
end
I put this code into application_helper.rb, and I can do updates from my
models. For example, with your schema, the code to call it would look like:
Families.find(family_id).people.update_attributes(person_id, :family_order
=> new_order)
Buyer beware- this is NOT heavily tested, and I''m pretty, so there may
be a
much better way to do this.
On 10/9/05, Brent Beardsley
<brentbeardsley-/E1597aS9LQAvxtiuMwx3w@public.gmane.org>
wrote:>
> Hi all,
>
> So I''m trying to setup the following:
>
> families table (habtm people)
> - has id, surname, display name
>
> people table (habtm families)
> - has id, given name, surname
>
> families_people
> - has family_id, people_id, family_order
>
> Now, I''ve figured out how to add a record in
> families_people (the join table) and update the
> family_order column using push_with_attributes.
>
> But now, I''m trying to update the family_order and
> reorder the people in the family if a person is moved
> up/down in the family order. How do I go about
> modifying family_order?
>
> Thank you for your help,
>
> Brent
>
>
>
>
>
> __________________________________
> Yahoo! Mail - PC Magazine Editors'' Choice 2005
> http://mail.yahoo.com
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
http://lists.rubyonrails.org/mailman/listinfo/rails