我有一个像这样的隐藏形式:
= form_for movie, 'create', method: 'POST' do |f|
- Movie.attribute_names.each do |attr|
= f.hidden_field attr.to_sym, value: movie.send(attr)
= f.submit 'Save this Movie', class: 'button'
其中一些属性是序列化数组,但 padrino 似乎不是从字符串解析数组,因此当我尝试从存储在 params 中的这个 attr 哈希中保存记录时,db 会引发序列化错误:
{"title"=>"Iron Man 2",
"directors"=>"[\"Jon Favreau\"]",
"cast_members"=>"[\"Robert Downey Jr.\", \"Gwyneth Paltrow\", \"Don Cheadle\", \"Scarlett Johansson\", \"Sam Rockwell\"]",
"genres"=>"[\"Action\", \"Adventure\", \"Sci-Fi\"]",
"length"=>"124",
"trailer_url"=>"http://imdb.com/video/screenplay/vi1172179225/",
"year"=>"2010",
"languages"=>"[\"English\", \"French\", \"Russian\"]"}
我可以用这段丑陋的代码来解析数组字符串:
Movie.serialized_attributes.keys.each do |k|
movie[k] = movie[k].gsub(/\"|\[|\]/, '').split(', ') if movie[k]
end
但这似乎很愚蠢,sinatra 应该自动解析它(或者不是?),或者我可能以错误的方式生成表单。我该如何解决这种行为?
注意:刚刚尝试生成这样的表单:
- Movie.attribute_names.each do |attr|
- if Movie.serialized_attributes.keys.include? attr
= f.hidden_field attr.to_sym, value: movie.send(attr), multiple: true
- else
= f.hidden_field attr.to_sym, value: movie.send(attr)