Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HABTM link tables not taking isolate_namespace value in mountable engine

I am currently developing a mountable engine. Within the engine I have the following two models:

  module Ems
    class Channel < ActiveRecord::Base
      has_and_belongs_to_many :categories
    end
  end

  module Ems
    class Category < ActiveRecord::Base
      has_and_belongs_to_many :channels
    end
  end

These are the db migration files:

  class CreateEmsChannels < ActiveRecord::Migration
    def change
      create_table :ems_channels do |t|
        t.string :slug
        t.string :name

        t.timestamps
      end
    end
  end

  class CreateEmsCategories < ActiveRecord::Migration
    def change
      create_table :ems_categories do |t|
        t.string :slug
        t.string :name
        t.text :strapline

        t.timestamps
      end
    end
  end


  class CreateEmsCategoriesChannels < ActiveRecord::Migration
    def up
      # Create the association table
      create_table :ems_categories_channels, :id => false do |t|
        t.integer :category_id, :null => false
        t.integer :channel_id, :null => false
      end

      # Add table index
      add_index :ems_categories_channels, [:category_id, :channel_id], :unique => true
    end
  end

The problem starts when I try to retrieve the associated objects. As an example, when I call @channel.get :categories I get the following error:

Mysql2::Error: Table 'ems_development.categories_channels' doesn't exist: 
SELECT `ems_categories`.* 
FROM `ems_categories` 
INNER JOIN `categories_channels` 
ON `ems_categories`.`id` = `categories_channels`.`category_id` 
WHERE `categories_channels`.`channel_id` = 1

As you can see its missing off the isolate_namespace value on the link table, as it should look for the association on the table ems_categories_channels not categories_channels

Anyone had similar problems or am I missing something?

like image 473
luxerama Avatar asked Mar 21 '12 12:03

luxerama


1 Answers

You can explicitly set the join table name (per the documentation).

  module Ems
    class Channel < ActiveRecord::Base
      has_and_belongs_to_many :categories, :join_table => 'ems_categories_channels'
    end
  end

  module Ems
    class Category < ActiveRecord::Base
      has_and_belongs_to_many :channels, :join_table => 'ems_categories_channels'
    end
  end
like image 82
Walking Wiki Avatar answered Oct 31 '22 15:10

Walking Wiki