I want to create a permissions table (managing permits to enter a room) that links user and room
Reference type with user and task as columns
Constraint not to save when a set of (user_id, task_id) that already exists in the table is entered
I want to check on the console if this validation works properly
This validation can be achieved by using "uniqueness constraint".
This time it is a record of the operation on the console launched with rails c to see if this is implemented properly.
macOS Catalina 10.15.6
ruby 2.6.5
Rails 6.0.3.4
MySQL : 5.6.47
app/models/permission.rb
class Permission < ApplicationRecord
belongs_to :user
belongs_to :task
validates :user_id, uniqueness: { scope: :task_id }
end
By the way, this is a constraint on the application, and to be exact, it is necessary to set a constraint on the DB side as well (<a href-"https://railsguides.jp/active_record_validations.html#uniqueness:title"> Rails guide < From / a>). However, I do not understand it yet, so I will omit it this time.
I wanted to check the uniqueness constraint, so I executed the code according to the following flow.
Get existing records with Permission.find (number)
Assign to an appropriate variable
Check if it can be saved with the valid? Method
Expected to be "false"
I launched the console in the terminal and checked.
teminal
$ rails c
[1] > permission = Permission.find(1)
=> #<Permission:*** id: 1, user_id: 1, task_id: 1, ***>
[2] > new.valid?
=> true
It has become true ... I thought about the cause and changed the command.
[Cause] ▶ "find" is an ActiveRecord method that searches for existing records ▶ If you save this, will it look like an overwrite save?
【Change】 ▶ Directly type user_id and task_id
terminal
$ rails c
[1] > Permission.find(1)
=> #<Permission:*** id: 1, user_id: 1, task_id: 1, ***>
[2] > permission = Permission.new(user_id: 1, task_id: 1)
=> #<Permission:*** id: nil, user_id: 1, task_id: 1, ***>
[3] > permission.valid?
=> false
[4] > permission.errors.full_messages
=> "User has already been taken"
I was able to confirm that it was completely false.
Multiple key uniqueness constraint can be specified with scope option
Create a new record for confirmation
I was a little addicted to it, but I managed to get over it. To really understand, you need to know what's working behind save and valid.
I still have a lot to study, but I will keep it down one by one.
Qiita: uniqueness: Explanation of unique constraint method using scope
External blog: [Rails] Unique constraint method using multiple columns [uniqueness: scope]
Recommended Posts