# Why can't I save to a join table in a migration or rake task

**URL:** <https://www.ruby-forum.com/t/why-cant-i-save-to-a-join-table-in-a-migration-or-rake-task/103871>\
**Category:** Rails\
**Created:** [May 11, 2007, 5:00am UTC](https://www.ruby-forum.com/t/why-cant-i-save-to-a-join-table-in-a-migration-or-rake-task/103871 "2007-05-11T05:00:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![stepheneb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/71e660/32.png) [@stepheneb](https://www.ruby-forum.com/u/stepheneb)\
**Post date:** [May 11, 2007, 5:00am UTC](https://www.ruby-forum.com/t/why-cant-i-save-to-a-join-table-in-a-migration-or-rake-task/103871/1 "2007-05-11T05:00:03Z")

</div>

At 9:13 PM -0400 5/10/07, Chris H. wrote:

> where is member\_role coming from?
> 
> also, the save! is not necessary, as the \<\< method saves the data in  
> the join table.

Hi Chris,

Here’s is the rake task version. member\_role is a local variable with  
the value of a Role object with the title “member”.

desc “setup\_roles for users.”  
task :setup\_roles =\> :environment do  
anonymous\_role = Role.find\_or\_create\_by\_title(‘anonymous’)  
member\_role = Role.find\_or\_create\_by\_title(‘member’)  
mananger\_role = Role.find\_or\_create\_by\_title(‘manager’)  
author\_role = Role.find\_or\_create\_by\_title(‘author’)  
admin\_role = Role.find\_or\_create\_by\_title(‘admin’)  
User.find(:all).each {|u| u.roles \<\< member\_role; u.save! }  
anonymous = User.find\_by\_login(‘Anonymous’)  
anonymous.roles.each {|r| r.destroy }  
anonymous.roles \<\< anonymous\_role  
stephen = User.find\_by\_login(‘stephen’)  
stephen.roles \<\< admin\_role  
end

I added the save! just to see if saving the object to which the  
collection is related would make a difference. It didn’t and I should  
have deleted it from my example before posting the question.

After running the migration listed below and then running the rake task  
listed above I have just two entries in the table roles\_users, one for  
the anonymous user and one for me. If instead I run these two commands  
in script/console:

member\_role = Role.find\_or\_create\_by\_title(‘member’)  
User.find(:all).each {|u| u.roles \<\< member\_role }

The new entries are created in the roles\_users joint table for all the  
users.

Here’s the migration I keep running up and down:

class AddRolesUsers \< ActiveRecord::Migration  
def self.up  
create\_table “#{RAILS\_APPLICATION\_PREFIX}roles\_users”, :id =\> false,  
:force =\> true do |t|  
t.column “role\_id”, :integer  
t.column “user\_id”, :integer  
end  
end

def self.down  
drop\_table “#{RAILS\_APPLICATION\_PREFIX}roles\_users”  
Role.delete\_all  
end  
end

–

- Stephen B.  
Concord Consortium, [http://www.concord.org](http://www.concord.org)
