setting hstore in rails4, dynamic key/values

前端 未结 3 1057
名媛妹妹
名媛妹妹 2021-01-01 01:52

I\'m playing around with Hstore for the first time in a rails4 app, and I am using javascript in a form to build out dynamic form fields for the hstore column (:schema)

3条回答
  •  一个人的身影
    2021-01-01 02:29

    Here's a way that also allows deleting of the hstore keys by submitting empty parameters.

    In your ApplicationController add this method:

    # Returns the hstore keys to be whitelisted.
    #
    # @param key [Symbol] the name of the hstore field
    # @param params [Hash] the parameters for the hstore field
    #
    # @return [{Symbol => Array}, Symbol]
    def permit_hstore_params(key, hstore_params)
      keys = hstore_params.try(:keys)
    
      # Return key if params are empty, 
      # this allows the hstore key to be removed.
      return key if keys.blank?
    
      # Otherwise, return the keys to be whitelisted
      { key => keys }
    end
    

    Example:

    class DynamicRecord < ActiveRecord::Base
      store_accessor :metadata
    end
    
    class DynamicRecordController < ApplicationController
      # ...
    
      def dynamic_model_params
        params
          .require(:dynamic_model)
          .permit(:name, permit_hstore_params(:metadata, params[:dynamic_model][:metadata]))
      end
    end
    

提交回复
热议问题