# Automatic update with has\_and\_belongs\_to\_many (:through)

**URL:** <https://www.ruby-forum.com/t/automatic-update-with-has-and-belongs-to-many-through/88441>\
**Category:** Rails\
**Created:** [March 11, 2007, 2:33am UTC](https://www.ruby-forum.com/t/automatic-update-with-has-and-belongs-to-many-through/88441 "2007-03-11T02:33:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![leonb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/22d042/32.png) [@leonb](https://www.ruby-forum.com/u/leonb)\
**Post date:** [March 11, 2007, 2:33am UTC](https://www.ruby-forum.com/t/automatic-update-with-has-and-belongs-to-many-through/88441/1 "2007-03-11T02:33:42Z")

</div>

Hi,

I have an application with a relation (many to many) via a :through. I  
want this to be automatically updated just like with a regular  
many\_to\_many. Just like I read here:  
[http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM](http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM)

Is this possible? I just can’t get it to work…

Here are my models:

class Declaration \< ActiveRecord::Base  
#Foreign key is niet nodig, maar wordt wel aangeraden  
belongs\_to :owner, :class\_name =\> ‘User’, :foreign\_key =\> ‘user\_id’  
has\_many :declarations\_payers  
has\_many :users, :through =\> :declarations\_payers

validates\_presence\_of :user\_id  
validates\_numericality\_of :user\_id  
validates\_presence\_of :amount  
validates\_numericality\_of :amount  
validates\_presence\_of :description

validates\_associated :owner  
validates\_associated :users

end

class DeclarationsPayer \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :declaration

validates\_presence\_of :declaration\_id  
validates\_numericality\_of :declaration\_id  
validates\_presence\_of :user\_id  
validates\_numericality\_of :declaration\_id

validates\_associated :user  
validates\_associated :declaration  
end

class User \< ActiveRecord::Base  
has\_many :deposits  
has\_many :declarations\_users  
has\_many :declarations, :through =\> :declarations\_users  
has\_many :my\_declarations, :class\_name =\> ‘Declarations’, :through  
=\> :declarations\_users

def fullname  
return self.firstname + ’ ’ + self.lastname  
end

end

Is it possible to add a new controller and automatically add the  
appropriate users in the declarations\_payers table?  
Is was trying to do something like this:  
\<%= check\_box\_tag ‘declaration[declarations\_payer.user]’, user.id %\>

But it just didn’t work…

Look here for my previous question about this application:  
[http://groups.google.com/group/rubyonrails-talk/browse\_thread/thread/6fe2827af57a4123](http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/6fe2827af57a4123)

Thanks in advance!
