0

有这些关系:我如何动态白名单键hstore在嵌套模式

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 

感谢您的任何帮助。

回答

3

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。与hstores合作有相当不错的article。还有一些一般的东西在使用hstore in Rails 4

+0

看起来这两个示例在hstore列中都有可预测的键。此应用程序具有动态的用户定义的密钥。请让我知道如果我读错了。 – ricsrock

+0

你说得对。提供我的定制解决方案 – Leger

+0

非常感谢! – ricsrock