I have a model Document
in my rails application. It has columns name
, and key
.
In my controller for create
action, I get document name from the frontend and dynamically set one value for key
with securerandom
.
The implementation I have for this case is:
Document model
class Document < ApplicationRecord
belongs_to :user
validates :key, presence: true, uniqueness: true
end
Documents Controller
class DocumentsController < ApplicationController
def create
current_user.documents.create(create_document_params)
redirect_to '/'
end
private
def create_document_params
params.require(:document).permit(:name).merge(key: "#{SecureRandom.hex(6)}#{Time.now.to_i}")
end
end
The problem with this approach is that the dynamic key logic is in the controller which I think should be the part of the Document model.
For that, I tried using Active Record Callbacks
inside the Document
model with before_create
.
I moved the securerandom key logic to the Document model like this:
class Document < ApplicationRecord
belongs_to :user
validates :key, uniqueness: true
before_create do
self.key = "#{SecureRandom.hex(6)}#{Time.now.to_i}"
end
end
But now my problem is, whenever I call create
or new
key
value is always the same. But it should be randomly generated before every create
call.
In the rails console
u = User.find_by(user_name: "random")
u.documents.new(name: 'Yolo 1') // key: "89c9013c191a1589398865"
u.documents.new(name: 'Yolo 2') // key: "89c9013c191a1589398865"
What I am doing wrong?
Edit: Added Gemfile :
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.3'
gem 'rails', '~> 6.0.3'
gem 'sqlite3', '~> 1.4'
gem 'puma', '~> 4.1'
gem 'sass-rails', '>= 6'
gem 'webpacker', '~> 4.0'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.7'
gem 'bcrypt', '~> 3.1.7'
gem 'bootsnap', '>= 1.4.2', require: false
group :development, :test do
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.2'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
gem 'webdrivers'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem "rspec-rails", "~> 4.0"
DB Migration:
class CreateDocuments < ActiveRecord::Migration[6.0]
def change
create_table :documents do |t|
t.string :name,
t.string :key, index: {unique: true}, null: false
t.references :user
t.timestamps
end
end
end