【问题标题】:How to whitelist dynamic hstore keys in a nested model如何将嵌套模型中的动态 hstore 键列入白名单
【发布时间】:2013-10-29 06:50:48
【问题描述】:

我有这些关系:

class Applicant < ActiveRecord::Base
  has_many :answers
  accepts_nested_attributes_for :answers
end

class Answer < ActiveRecord::Base
  belongs_to :applicant
end

答案模型有一个称为属性的 hstore 属性。属性哈希将具有动态键,因为它们是由用户在应用程序中创建的。

我似乎无法在申请者控制器中成功地将这些动态密钥列入白名单。

这是我目前(不成功)的尝试。

def applicant_params
  params.require(:applicant).permit(:answers_attributes: [:question_id, :id]).tap do |whitelisted|
        whitelisted[:answers_attributes][:properties] = params[:applicant][:answers_attributes][:properties]
    end
end

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails-4 nested-attributes strong-parameters hstore


    【解决方案1】:

    UPD。尝试使用以下方法(在单独的文件中测试):

    @params = ActionController::Parameters.new(
      applicant: {answers_attributes: { 
                    "0" => {question_id: 10, id:  110, properties: {a: "b", c: "d"}}, 
                    "1" => {question_id: 20, id:  120, properties: {m: "n", o: "p"}}
    }})
    
    def applicant_params
      #properties should be [:a, :c, :m, :o]
      properties = []
      @params[:applicant][:answers_attributes].values.each do |answer|
        properties |= answer[:properties].keys
      end
      @params.require(:applicant).permit(answers_attributes: 
                                           [:question_id, :id, properties: properties])
    end
    

    BTL。 article 与 hstores 合作非常好。还有一些关于使用hstore in Rails 4 的一般事项。

    【讨论】:

    • 看起来这两个示例在 hstore 列中都有可预测的键。这个应用程序有动态的、用户定义的键。如果我读错了,请告诉我。
    • 虽然这应该可行,但它不是 Rails 方式:stackoverflow.com/a/19059398/781704
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多