'Active record querying with store_accesors

I have a database where I need to do a search on specific record that has a certain output. What is making this tricky for me is that these values are found in a 'store_accessor' and therefore they aren't always there.

For instance if I run Team.last.team_configuration, I get this value below, and what I need are only teams that have a specific setting.

<TeamConfiguration:0x00007123456987> {
        :id => 8,
  :owner_id => 6,
:team_type => "football",
  :settings => {
      "disable_coach_add" => false,
    "delink_players_at_18" => true
},
      :type => "TeamConfiguration"

}

My thoughts have been something around these lines, but i keep getting undefined method 'settings' for team_configuration:Symbol

Team.where(:team_configuration.settings['delink_players_at_18'])

Would anyone know what I am doing wrong in this instance? I think because there are two separations from the main source it has been causing me some issues. Thanks in advance!



Solution 1:[1]

The problem is way store_accesors works, look what documentation says:

Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It's like a simple key/value store baked into your record when you don't care about being able to query that store outside the context of a single record.

https://api.rubyonrails.org/classes/ActiveRecord/Store.html

So a posible solution could be to search by that column, converting a previously hash of what you want to string.

Team.where(team_configuration: data.to_s)

Solution 2:[2]

If you're using a postgres database and the TeamConfiguration#settings column is serialized as jsonb column you can get at this with postgres json operators:

Team.joins(:team_configurations)
  .where("team_configurations.settings @> '{\"delink_players_at_18\": true}'")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Javier Menéndez Rizo
Solution 2 bradley2w1dl