简体   繁体   中英

Rails migration with unique index, null: false, default: “”

I have a subdomain column in my project table. I allow premium users to update the subdomain and free users cannot update it. I also want unique subdomains so that there is no conflict. Currently, I have a setup like this:

Project migration

create_table :projects, id: uuid do |t|
  t.string :name, null: false, default: ""
  t.string :subdomain, null: false, default: ""
end

add_index :projects, :subdomain, unique: true

project.rb (model)

validates :subdomain, length: { maximum: 63 }, uniqueness: { case_sensitive: false, allow_blank: true }

The problem is if the free user updates the project table 's name attribute, the subdomain is passed as an empty string as param , and with my current setup, it is not possible for another free user to update the project table as the user would also pass in an empty string for the subdomain column and would result in an error.

Currently, I am fixing this bug by overwriting the subdomain= method, removing the null: false , and removing the default: "" from the subdomain column

def subdomain=(value)
  default_value = value.blank? ? nil : value
  super(default_value)
end

I know I can also overwrite the param hash, but I want to know if there are any other solutions to this. I am willing to change my migration as well.

You can try this:

  • Add nullable subdomain field with unique index; null: true
  • Add:
   validates :subdomain, length: { maximum: 63 }, uniqueness: { case_sensitive: f 
 alse }, allow_nil: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM