带有数组的Rails ActiveRecord find_by

时间:2019-05-27 15:41:50

标签: mysql ruby-on-rails ruby activerecord

我的rails应用程序中有一个Blacklist表,下面是在rails console中运行命令时其中的示例数据:

# rails console
Blacklist.all

#<Blacklist id: 1, auth_tokens: ["abc", "abc1", "abc2"], user_id: 2, created_at: "..", updated_at: "..">
#<Blacklist id: 2, auth_tokens: ["xyz", "xyz1", "xyz2"], user_id: 1, created_at: "..", updated_at: "..">

当我跑步时:

# rails console
Blacklist.find_by(auth_tokens: "abc")
# returns nil

现在,我要查找包含值auth_token-"abc"->的黑名单,即查询应返回ID为1的Blacklist。如何实现呢?

编辑:schema.rb文件

create_table "blacklists", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.text "auth_tokens"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

然后auth_tokens在Model中进行序列化:

# Blacklist model
serialize :auth_tokens

after_initialize do |blacklist|
  blacklist.auth_tokens = [] if blacklist.auth_tokens == nil
end

0 个答案:

没有答案