Reputation: 35
I have 3 tables and I want to create new table that stores the following:
user_id
project_id
company_id
I've tried through this command, but it does not work:
rails g migration CreateJoinTableUserProjectCompany
user:referencess project:referencess company:referencess
What do you recommend?
Upvotes: 1
Views: 113
Reputation: 9443
I'm not actually sure how generate the migration to create a join table with only those three columns, and id column. Obviously we can edit the generated migration and edit it (which I'll do in my answer), but where's the fun in that?
That having been said, and all fun apparently removed, I'd suggested creating an entire table, including id column, even though you may not think you need it. It may come in handy (which of these two u-p-c's was created first, I need to put this model in a nested form, etc.). To create a table that includes the id, you can simply run the following command.
rails g migration CreateUserProjectCompany user:references project:references company:references
Running the created migration will create a table that looks like:
id | user_id | project_id | company_id
To create the table without id, you'll unfortunately need to edit the migration. Replace this line...
create_table :user_project_companies do |t|
...with this one.
create_table :user_project_companies, id: false do |t|
I.E., add , id: false
after the table name, which specifies that the table should not have an id
column. Running this migration will give you that table with only the three columns.
user_id | product_id | company_id
Upvotes: 1
Reputation: 1954
Generating a migration alone does not use the column parameters unless you want to add or remove a column to an existing model. You would need to generate a model to accomplish what you are trying to do (almost). For example:
rails g model UserProjectCompany user:references project:references company:references
This will generate following migration:
class CreateUserProjectCompanies < ActiveRecord::Migration
def change
create_table :user_project_companies do |t|
t.references :user
t.references :project
t.references :company
t.timestamps
end
add_index :user_project_companies, :user_id
add_index :user_project_companies, :project_id
add_index :user_project_companies, :company_id
end
end
But do note that you will have to add :id => false
and remove t.timestamps
if you don't need those.
Another thing is that it will also generate a model named "UserProjectCompanies" and some specs for it.
Upvotes: 1
Reputation: 1601
Hey you made typo error referencess, instead use references
rails g migration CreateJoinTableUserProjectCompany user:references project:references company:references
Upvotes: 0