在rails4中设置hstore,动态键/值

我在rails4应用程序中第一次使用Hstore,我在表单中使用javascript来构建hstore列的动态表单字段(:schema)

在rails 4中,我不需要在我的模型中添加任何setter / getter方法,对吗?

在我的表单中,我正在构建动态输入字段,并允许用户设置键/值对。 很像Hstore Heroku演示应用程序

所以基本上我的表格会有输入

input name="app[schema][dynamic_key1]" value="whatever value" input name="app[schema][dynamic_key2]" value="whatever value2" 

在我的App Controller中:

 def app_params params.require(:app).permit(:name, :title, :schema ) end 

但是,当我创建新的App记录时,我的架构hstore值不会保存。 我看到了一些关于制作强大的参数的东西:schema => []但是仍然无效。

由于我不知道这些值是什么,我无法为这些设置store_accessors,就像我在很多例子中看到的那样。

在这里找到了这个: http : //guides.rubyonrails.org/action_controller_overview.html#more-examples

在我的控制器中我用过:

 def app_params params.require(:app).permit(:name, :title).tap do |whitelisted| whitelisted[:schema] = params[:app][:schema] end end 

这是一种允许通过提交空参数来删除hstore密钥的方法。

在ApplicationController中添加此方法:

 # 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 

例:

 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