Iain
Iain

Reputation: 127

Caching of Classes / Object lists in Ruby on Rails

I have two classes, a User and a UserGroup class.

A User has one UserGroup and a UserGroup can have many Users

When I create a new UserGroup, say "Group 1", it appears in my list of UserGroups and I can edit it and save it without problems.

However, when I go to create a new User, I can see and select my new UserGroup, "Group 1" from the dropdown list, but when I go to save I get a validation error because Rails doesn't see the UserGroup id as belonging to the current list of UserGroup ids.

Here are pieces of what I believe are the relevant code:

user_group model:

class UserGroup < ActiveRecord::Base
  ...
  ...
  # class methods
  def self.full_list_of_ids
    UserGroup.all.pluck(:id)
  end
end

user model:

class User < ActiveRecord::Base
  ...
  ...
  validates :user_group_id, inclusion: { in: UserGroup.full_list_of_ids }, unless: 'Rails.env.test?'
  ...
  ...
end

The error that occurs when I try to save the new User with the new UserGroup is a validation error so it seems the code within full_list_of_ids returns back an older version of the UserGroup ids even although within the views, I can see the new UserGroup.

I am running this within my development environment at the moment.

So is there a way to force Rails to reload the version of UserGroups in memory or something else?

It seems like it's just caching things too much to me. Surely a newly created object within a class should cause a reload automatically?

I should point out that I can change the UserGroup of any User to an older UserGroup no problems.

If you need any more information, let me know. Thanks.

Upvotes: 1

Views: 355

Answers (1)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

In 11 years I haven't seen someone using an inclusion validation like this. What you want to do is according to the docs:

class User < ActiveRecord::Base
  belongs_to :user_group
  validate :user_group, presence: true
end

Now to explain why you ran into this problem: the argument of validate are evaluated when the class is loaded, so the UserGroup.full_list_of_ids is evaluated into an array and that array is not updated after creating a new usergroup. Don't ask for a work-around, use the presence validator instead.

Upvotes: 2

Related Questions