Rails 4:如何使用Store(序列化存储哈希)在哪里?

时间:2016-04-19 16:10:19

标签: ruby-on-rails ruby-on-rails-4 serialization hash store

我正在使用Rails4的商店功能。我添加了一个新的存储属性,即“朋友”,有四个访问者,第一个...第四个。

问题是如何在“where”条件下使用它。当我用它时:

@persons = Person.where(friends.has_value?@user.id) 

我收到此错误:

NameError in UsersController#myfrineds
undefined local variable or method `friends'

我尝试了其他一些不同的方法,但我仍然得到错误。你能帮我解决一下吗?或者如果您有任何更好的想法实现它(请存储键/值的动态哈希),请告诉我?

2 个答案:

答案 0 :(得分:1)

Uzbekjon 所述,商店不适用于此类事情。解决问题的一些方法:

  • 使用自定义查询(根据表格大小会很慢,所以要小心):

    @persons = Person.where('friends LIKE ? OR friends LIKE ? OR friends LIKE ? OR friends LIKE ?', "%first: #{@person.id}\n%", "%second: #{@person.id}\n%", "%third: #{@person.id}\n%", "%fourth: #{@person.id}\n%")
    

    这假设您使用 yaml 进行friends属性的序列化(它是默认值)。如果您使用 json ,则必须相应地更改查询。

  • 如果您正在使用PostgreSQL,则可以使用数组属性而不是存储。由于PostgreSQL支持这种数据类型,因此查询将有更好的时间。

    迁移:

    def change
      add_column :people, :friends, :text, array: true, default: []
    
      # if you want to add index:
      add_index  :people, :friends, using: 'gin'
    end
    

    创建记录:

    Person.create(..., friends: [friend_id_1, friend_id_2, friend_id_3, friend_id_4])
    

    查询:

    @persons = Person.where('? = ANY(friends)', @person.id)
    

    您可能还需要添加到 Gemfile

    gem 'postgres_ext'
    

希望它有所帮助!

答案 1 :(得分:0)

简短回答 - 你不能!因为,ActiveRecord将您的“哈希”存储为单个列中的字符串。我能想到的唯一方法是使用.where("friends LIKE :friend", friend: 'BFF')语法。不要忘记为列编制索引。

它也是mentioned in the docs

  

当你不关心能够在单个记录的上下文之外查询该商店时,它就像是一个简单的键/值存储到你的记录中