使用store_accesors进行活动记录查询

时间:2019-01-09 21:25:09

标签: ruby-on-rails activerecord

我有一个数据库,需要在其中搜索具有特定输出的特定记录。使我感到棘手的是,这些值是在“ store_accessor”中找到的,因此它们并不总是存在。

例如,如果我运行Team.last.team_configuration,则会在下面获得此值,而我只需要具有特定设置的团队。

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

}

我的想法一直围绕着这些思路,但是我不断得到undefined method 'settings' for team_configuration:Symbol

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

有人会知道我在这种情况下做错了什么吗?我认为,由于与主要来源有两种分离,这一直导致我遇到一些问题。预先感谢!

1 个答案:

答案 0 :(得分:0)

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)