目前,我有一个form_tag,其中包含输入并将这些输入放入参数中。 我希望能够在控制器操作中遍历它们。
我尝试获取所有params
(不包括所有常规params
(动作,控制器,模型名称等),然后使用通配符,如params[:prop*]
。
这是有问题的表单输入:
%input{:name => "userEmails", :id =>"userEmails", :type => "hidden", :value => ""}
-@all_properties.each do |prop|
%input{:name => "prop"+prop.name+"checkbox", :type => "checkbox", :id => "prop"+prop.name+"checkbox"}
#{prop.name}
%input{:name => "prop"+prop.name, :type => "text", :id => "prop"+prop.name}
这些出现在{"propProperty1checkbox"=>"on", "propProperty1" => "testing", "propAnotherPropertycheckbox" => "on", "propAnotherProperty" => "another test value"}
等参数中。
我不确定如何访问这些属性,因为属性名称可以更改,因此需要抽象访问。
答案 0 :(得分:1)
您可以在#select
哈希上使用params
来仅过滤您感兴趣的参数:
params = {"user_id"=>1,
"propProperty1checkbox"=>"on",
"propProperty1"=>"testing",
"propAnotherPropertycheckbox"=>"on",
"propAnotherProperty"=>"another test value"
}
params.to_h.select{|key, value| key =~ /^prop/}
#=> {"propProperty1checkbox"=>"on",
#"propProperty1"=>"testing",
#"propAnotherPropertycheckbox"=>"on",
#"propAnotherProperty"=>"another test value"}
编辑
评论示例:
[13] pry(main)> {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"xxxxx", "userEmails"=>"teste@test.com,test2@test.com,test4@test.com,fasd@gmail.com", "propProperty1checkbox"=>"on", "propProperty1"=>"3", "propAnotherPropertycheckbox"=>"on", "propAnotherProperty"=>"4", "commit"=>"Submit", "Application"=>"8", "Company"=>"1" }.to_h.select{|k, v| k =~ /^prop/}
=> {"propProperty1checkbox"=>"on",
"propProperty1"=>"3",
"propAnotherPropertycheckbox"=>"on",
"propAnotherProperty"=>"4"}
答案 1 :(得分:1)
您可以尝试以下操作:
input(name: "props[#{pro_name}][checkbox]"...)
input(name: "props[#{pro_name}][text]"...)
然后,在您的控制器中:
def method
props = params[:props]
props.each do |property_name, values|
chk = values[:checkbox]
text = values[:text]
end
end