In the migration, provide the option to include a constraint to match the "only 1 primary" rule.
mechanicles opened this issue · 0 comments
In the generator code:
# lib/generators/set_as_primary/set_as_primary_generator.rb (line 11)
argument :table_name, type: :string
We need to provide an extra option(argument) which supports handling of only one true
value (constraint) in the table. Something like this: https://stackoverflow.com/questions/28166915/postgresql-constraint-only-one-row-can-have-flag-set
We also need to handle that option in the migration template file:
# lib/generators/set_as_primary/templates/migration.rb (lines 1-5)
class AddPrimaryColumnTo<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %>
def change
add_column :<%= table_name.to_sym %>, :primary, :boolean, default: false, null: false
end
end
This support should work on PostgreSQL, MySQL, and SQLite. BTW, currently, our gem handles this issue automatically, but still, we should not ignore DB constraint.
To solve this, you need to learn how to write a generator and how to pass extra option to the generator. For running the generator command, please check the README file.
You can also use this Rails app https://github.com/mechanicles/set_as_primary_rails_app for testing the generator command.
Feel free to ask me any questions if you have.