【问题标题】:Rails 4 ActiveRecord: How to drill down to nested 3 layer record and see if an array contains stringRails 4 ActiveRecord:如何深入到嵌套的 3 层记录并查看数组是否包含字符串
【发布时间】:2016-05-11 02:32:22
【问题描述】:

所以我有一个嵌套的活动记录,其中包含一个哈希数组。我正在尝试使用存储在数组中的一个元素中的国家/地区代码在我正在制作的应用程序中获取国家/地区。

记录被描述:

user.rules.first.countries.first["country_code"]

用户有_许多规则,

rules 包含一个名为 countries 的 jsonb 列

countries 是一个 jsonb 哈希数组

目前我正在遍历所有这些以查找记录。例如

country_code_to_find = "US"
user.rules.each do |r|
  r.countries.each do |c|
    if c["country_code"] == "US"
      # Do some stuff
    end
  end
end

有没有一种方法可以使用 .where() 或范围或类似的东西通过单行访问该国家/地区?我正在使用 rails 4、activerecord 和 postgres。

【问题讨论】:

    标签: ruby-on-rails arrays postgresql ruby-on-rails-4 activerecord


    【解决方案1】:

    在不了解 JSON 结构的情况下,我不确定您是否可以通过单个查询访问“那个国家/地区”,因为“国家/地区”是数组中的一个元素。您可以查询包含所需“国家/地区”的规则对象。像这样的东西可能会起作用

    user.rules.where("
      countries @> '[{\"country_code\": \"US\"}]'
    ")
    

    根据您的业务逻辑,知道该用户至少有一条 country=US 的规则就足够了。

    country_code_to_find = "US"
    if user.rules.where("countries @> '[{\"country_code\": \"#{country_code_to_find}\"}]'").exists?
      # Do some stuff
    end
    

    More on Postgres' JSONB functions.

    这些问题看似相关,但并非特定于 Rails:

    Postgresql query array of objects in JSONB field.

    Query for array elements inside JSON type

    【讨论】:

      【解决方案2】:

      使用 messenjah 的答案,我得到了一个可行的解决方案。必须找到数组的索引,这样我才能使用它。为了提供更多关于 messenjar 的信息,这里是 json:

      countries: [{"code"=>"US", "name"=>"United States", "states"=>{"NY" => "New York"}}, {"code"=>"MX", "name"=>"Mexico", "states"=>{"YUC" => "Yucatán"}}]
      

      然后获取我使用的状态数组:

      country_code = "MX"
      rule = @user.rules.where("countries @> '[{\"code\": \"#{country_code}\"}]'").first    
      country_index = rule.countries.index {|h| h["code"] == country_code  }
      states = rule.countries[country_index]["states"]
      

      基本上这会得到我想要的哈希数组的索引。不确定这是否比我开始使用的更好或更差。但它有效。如果他们能解决这个问题,很高兴考虑其他答案。

      【讨论】:

        猜你喜欢
        • 2020-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 2016-01-31
        • 2012-01-22
        相关资源
        最近更新 更多