Last active
May 9, 2020 08:36
-
-
Save jean-francois-labbe/5578c98f29edf82f66ae31d2a4f69853 to your computer and use it in GitHub Desktop.
Rails enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin | |
require "bundler/inline" | |
rescue LoadError => e | |
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" | |
raise e | |
end | |
gemfile(true) do | |
source "https://rubygems.org" | |
gem "activerecord" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :users do |t| | |
t.integer :access_type, default: 0 | |
t.datetime :blocked_at | |
end | |
end | |
class User < ActiveRecord::Base | |
enum access_type: [:authorized, :blocked] | |
end | |
user = User.new | |
p user.access_type | |
user.save! | |
user.reload | |
def block(user) | |
user.blocked! # This will update the database record | |
user.blocked_at = Time.now # This wont update the database record | |
end | |
block(user) | |
puts "access_type value is" | |
p User.first.access_type # The access_type as been updated even though save was not called | |
puts "blocked_at value is" | |
p User.first.blocked_at # The blocked_at is not set. | |
# If in the block method we call save, such as below, it will update the record twice in the database. | |
# One call to set the access_type another to set the blocked_at | |
def block(user) | |
user.blocked! # This will perform one update query | |
user.blocked_at = Time.now | |
user.save # This will perform one update query | |
end | |
# If we want to perform only one query, we have to use the enum string value to the access_type value. | |
# the function would be | |
def block(user) | |
user.access_type = "blocked" # This will just set the access_type value to blocked | |
user.blocked_at = Time.now | |
user.save # This will perform one update query | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My question is, How to set an
enum
to a specific value without saving it to db, so that it is possible to update other attributes and then call thesave
method to perform the db update.