我的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