【问题标题】:Rails - Search by store attributes in modelRails - 按模型中的商店属性搜索
【发布时间】:2015-09-14 14:38:48
【问题描述】:

我如何使用 :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

【问题讨论】:

    标签: mysql configuration store


    【解决方案1】:
    Product.where("token = ?", callback_params[:token].to_yaml, callback_params[:code].to_yaml)
    

    阅读本文以获取更多信息: Searching serialized data, using active record

    【讨论】:

      【解决方案2】:

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

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

      为了进行搜索,我在 Rails API 中没有找到任何提供它的功能。由于不适合在 store 上使用搜索,我使用 SQL 自己的资源进行查询

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

      可以轻松地将其转换为泛型方法并放入一些抽象类中,但大致就是这样

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 2014-11-21
        • 1970-01-01
        • 2016-12-29
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 1970-01-01
        相关资源
        最近更新 更多