Forum: Ruby on Rails why can't I save to a join table in a migration or rake task

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
5810a1b7743eb2186ca0ea1d0a3469a0?d=identicon&s=25 Stephen Bannasch (Guest)
on 2007-05-11 05:00
(Received via mailing list)
At 9:13 PM -0400 5/10/07, Chris Hall 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;! }
    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

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

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

  def self.down
    drop_table "#{RAILS_APPLICATION_PREFIX}roles_users"

- Stephen Bannasch
  Concord Consortium,
This topic is locked and can not be replied to.