Reputation: 79
I have some issues. I'm new to RoR
I'm trying to create a join table using Rails migration. Documentation of this is here... http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_join_table
When I do...
rails g migration CreateJoinTableUserOffer users offers
...it creates the following migration
class CreateJoinTableUserOffer < ActiveRecord::Migration
def change
create_join_table:users, :offers do |t|
t.index [:user_id, :offer_id]
t.index [:offer_id, :user_id]
end
end
end
and when I do...
rake db:migrate
it creates...
-- Table: offers_users
-- DROP TABLE offers_users;
CREATE TABLE offers_users
(
user_id integer NOT NULL,
offer_id integer NOT NULL
)
WITH (
OIDS=FALSE
);
ALTER TABLE offers_users
OWNER TO sudeepkaushik;
-- Index: index_offers_users_on_offer_id_and_user_id
-- DROP INDEX index_offers_users_on_offer_id_and_user_id;
CREATE INDEX index_offers_users_on_offer_id_and_user_id
ON offers_users
USING btree
(offer_id, user_id);
-- Index: index_offers_users_on_user_id_and_offer_id
-- DROP INDEX index_offers_users_on_user_id_and_offer_id;
CREATE INDEX index_offers_users_on_user_id_and_offer_id
ON offers_users
USING btree
(user_id, offer_id);
What I want to do is that I first of all want the table name to be users_offers instead of offers_users, for this you can specify the :table_name in the create_join_table migration. I'm not able to get the syntax of setting this option correctly. Need help here!
2nd, I noticed that this migration doesn't create the foreign keys that I would expect with the Users and Offers tables. Need your comments here also. Do I need to manually create the foreign keys myself?
Upvotes: 4
Views: 3083
Reputation: 8498
You can define your join tables name with the table_name
option.
create_join_table :users, :offers, table_name: :users_offers
There is also an option for setting column options called column_options
, but I only got it to work for indexes and not for foreign keys.
create_join_table :users, :offers, column_options: { index: true }
This will create the desired indexes, but it ignores foreign_key: true
. So you need to create them separately.
add_foreign_key :users_offers, :users
add_foreign_key :users_offers, :offers
In your models you need to add the relation like this:
# user.rb
has_and_belongs_to_many :offers, join_table: :users_offers
And:
# offers.rb
has_and_belongs_to_many :users, join_table: :users_offers
Upvotes: 9