1

I want a HomePage model to be a Singleton class, as i want only one instance of the HomePage model. So this is what I did:

require 'singleton' class HomePage < ApplicationRecord include Singleton has_one_attached :image end 

In HomePagesController, I want the users to be able to edit the unique instance of the HomePage model. So, i did something like this:

class HomePagesController < AdminDashboardsController def edit @home_page = HomePage.instance end end 

Problem:

The default value that HomePage.instance returns nil. I am guessing that the instance is not persisted, as it returns false for the presisted? method call.

I want to be able to create the unique instance for the first time, i.e. override the nil instance that I get from HomePage.instance using seed data, or rails console, and then give the user the ability to edit that instance for as long as they want, using the HomePage Controller as shown in above code.

What i tried:

I tried updating the initial unique instance of the HomePage model, by calling HomePage.instance.update(name: "Hello"). This seemed to create a different instance with id:2, rather than overwriting the previous unique object.

Am I missing out on something? Or am I misunderstanding the overall use of Singleton class itself?

1 Answer 1

2

The problem is that singleton is about Ruby object, not about record in the database. And because of multi-threading the processes in Rails are isolated

So if you need to keep just one record don't use require 'singleton'

Define method

def self.get first || create # more Rails way - first_or_create end 

or

def self.get first || new # more Rails way - first_or_initialize end 

And in your code call HomePage.get

Sign up to request clarification or add additional context in comments.

1 Comment

Or maybe you could implement def self.new ; first || super ; end and keep the singleton.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.