Rails migration create_join_table with uuids

Newer versions of rails allow you to specify that tables should be created using the uuid primary key as follows:

create_table :foos, id: :uuid do |t| # ... end 

It's great. And over time, the rails supported the creation of join tables like this:

 create_join_table :foos, :bars do |t| # ... end 

Also great. In addition, my tables have uuid primary keys and generate foreign key columns of type integer instead of type uuid.

Looking back at the documentation for create_join_table , I cannot find anything obvious to change the type of the column. Is it possible to use create_join_table with uuids?

Or I can create the connection table manually:

 create_table :bars_foos, id: false do |t| t.uuid :bar_id t.uuid :foo_id end 
+5
source share
3 answers

I needed to see the code ...

 def create_join_table(table_1, table_2, options = {}) join_table_name = find_join_table_name(table_1, table_2, options) column_options = options.delete(:column_options) || {} column_options.reverse_merge!(null: false) t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key } create_table(join_table_name, options.merge!(id: false)) do |td| td.integer t1_column, column_options td.integer t2_column, column_options yield td if block_given? end end 

Columns are explicitly created as integers without the possibility of changing them. Too bad...

+5
source

Inside Rails 5.0 you can use the optional column_options option in the column_options method to specify the type of identifier columns. Then your migration will look like this:

 create_join_table :foos, :bars, column_options: {type: :uuid} do |t| t.index [:foo_id, :baar_id] end 
+4
source

Cannot create connection tables with uuids.

As pointed out in the create_table question, this is the only option. The best way to emulate create_join_tables with uuid is to use create_tables as follows:

  • Run: rails g migration CreateFoosBars bars:references foos:references
  • The command will create the following output, which you will need to change

generate output

 class CreateBarFoos < ActiveRecord::Migration def change create_table :bars_foos, id: :uuid do |t| t.references :bars, foreign_key: true t.references :foo, foreign_key: true end end end 
  • Change id: uuid => id: false
  • Add type: uuid, index: true at the end of the links

final migration

 class CreateBarFoos < ActiveRecord::Migration def change create_table :bars_foos, id: false do |t| t.references :bars, foreign_key: true, type: :uuid, index: true t.references :foo, foreign_key: true, type: :uuid, index: true end end end 

It would be nice if Rails can add additional support for different types of identifiers in create_join_table , it can even be derived from an existing migration.

Until then, I hope these steps will achieve the same result.

0
source

Source: https://habr.com/ru/post/1232815/


All Articles