Rails - 按模型中的商店属性搜索

Rails - Search by store attributes in model

我如何使用 :token 和 :external_code

进行搜索
class Product < ActiveRecord::Base
    belongs_to :admin
    has_many :lessons
    store :config, accessors: [:token, :external_code]

    has_attached_file :logo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :logo, :content_type => /\Aimage\/.*\Z/

end

我试过了

prod = Product.find_by({
        token: callback_params[:token],
        external_code: callback_params[:code]
     })

但是...这个错误

Mysql2::Error: Unknown column 'products.token' in 'where clause': SELECT `products`.* FROM `products` WHERE `products`.`token` = 'Q1LhyCrBsYqt57tRVUgnjmHbyZ0zf81110916' AND `products`.`external_code` = '320552' LIMIT 1
Product.where("token = ?", callback_params[:token].to_yaml, callback_params[:code].to_yaml)

阅读此内容了解更多信息: Searching serialized data, using active record

您必须先为您的商店格式定义一个

store :config, accessors: [:token, :external_code], coder: JSON

为了进行搜索,我在 Rails API 中找不到任何内容。由于不适合在商店中使用搜索,因此我使用了 SQL 自己的资源来进行查询

Product.where("products.config LIKE ? and products.config LIKE ? ", '%"token":"meu token"%', '%"external_code":"meu code"%')

可以轻松地将其转换为通用方法并放入一些抽象内容 class,但大致就是这样