So far, the field status can have values like valid, invalid, locked
etc., but it is not regarded yet by Rails. So I would like to integrate
it with the standard methods.
josh $ script/console
m = Member.find(:first)
m.disc_jockeys # Returns all associated disc jockeys
m.disc_jockeys(:status => ‘valid’) # Returns associated disc jockeys with the status valid
The 4th line above should change the query
SELECT * FROM disc_jockeys LEFT JOIN disc_jockeys_members ON
disc_jockeys.id = disc_jockeys_members.disc_jockey_id WHERE
(disc_jockeys_members.member_id = 25 )
to
SELECT * FROM disc_jockeys LEFT JOIN disc_jockeys_members ON
disc_jockeys.id = disc_jockeys_members.disc_jockey_id WHERE
(disc_jockeys_members.member_id = 25 and disc_jockeys_members.status =
‘valid’)
Now my question: What ActiveRecord method do I have to edit to reach
this goal?
You can’t update the attributes in the join table. You could remove
the object from the collection and then re-add it with the updated
status. Search the archives of the mailing list for more potential
solutions, as this topic has been discussed quite a bit.
Great, after hours of asking stupid questions I found out that my PDF is
corrupt and that it’s missing pages 241 to 252…
So now I found in the paper back version of the book that there’s a
push_with_attributes method that solves my problem. Thanks anyway.
You could remove
the object from the collection and then re-add it with the updated
status.
Thanks for that hint; but how can I tell Rails what status it should set
in the status field of the relationship table?
I searched the mailing lists, but didn’t really know what terms to
use… any suggestions?
I have added this code to my application.rb (just for testing purposes,
I will outsource it to lib later when it works), but the method is not
available!
This gives me a “NoMethodError: undefined method `update_attributes’ for
DiscJockey:Class”. I tried also this way:
class ActiveRecord::Associations::HasAndBelongsToManyAssociation
def update_attributes(record, join_attributes = {})
if record.is_a? ActiveRecord::Base
record_id = record.id
else
record_id = record
end
cols, vals = [], []
join_attributes.each do | key, val |
cols << key.to_s
vals << val
end
col_string = cols.join(’ = ?, ') @owner.connection().update(sanitize_sql([“UPDATE #{@join_table} SET
#{col_string} = ? WHERE #{@association_class_primary_key_name} = ? AND
#{@association_foreign_key} = ?”, vals, @owner.id, record_id].flatten),
“Update Attributes”)
end
end
But it doesn’t work… What’s wrong here? I don’t have to restart the
server when I place the stuff in controller/application.rb, do I?