迭代Params Hash

时间:2010-06-06 05:51:17

标签: ruby-on-rails ruby hash iteration params

我有一段非常令人沮丧的时间来上传一些图片。它们显然是作为机架/多部件上传的,但是我正在迭代我的params散列的方式必然会导致问题。我真的可以使用一些帮助,所以我可以停止拔头发。

所以我有一个看起来像这样的params哈希:

Parameters: {"commit"=>"Submit", "sighting_report"=>[{"number_seen"=>"1", "picture"=>#<File:/var/folders/IX/IXXrbzpCHkq68OuyY-yoI++++TI/-Tmp-/RackMultipart.85991.5>, "species_id"=>"2"}], "authenticity_token"=>"u0eN5MAfvGWtfEzrqBt4qfrL54VJ9SGX0jFLZCJ8iRM=", "sighting"=>{"sighting_date(2i)"=>"6", "name"=>"", "sighting_date(3i)"=>"5", "county"=>"0", "notes"=>"", "location"=>"", "sighting_date(1i)"=>"2010", "email"=>""}}

我的表单可以有多个目击报告,每个目击报告中都有多张图片。这是我的控制器代码:

def create_multiple
    @report = Report.new
    @report.name = params[:sighting]["name"]
    @report.sighting_date = Date.civil(params[:sighting][:"sighting_date(1i)"].to_i, params[:sighting][:"sighting_date(2i)"].to_i, params[:sighting][:"sighting_date(3i)"].to_i)
    @report.county_id = params[:sighting][:county]
    @report.location = params[:sighting][:location]
    @report.notes = params[:sighting][:notes]
    @report.email = params[:sighting][:email]
    @report.save!
    @report.reload
    for sr in params[:sighting_report] do
        sighting = SightingReport.new
        sighting.report_id = @report.id
        sighting.species_id = sr[:species_id]
        sighting.number_seen = sr[:number_seen]
        sighting.save
        if sr[:picture]
            sighting.reload
            for pic in sr[:picture] do
                p = SpeciesPic.new
                p.uploaded_picture = pic
                p.species_id = sighting.species_id
                p.report_id = @report.id
                p.save!
            end
        end
    end
    redirect_to :action => 'new_multiple'
end

我似乎无法访问图片数据本身,但继续访问某些字符串。虽然这不是文件名,但对于转义字符有些奇怪。如何访问实际数据?

1 个答案:

答案 0 :(得分:0)

您应该使用accepts_nested_attributes_for(如下所述:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

这将从控制器中删除所有复杂性,并允许一些Rails魔术来处理嵌套对象创建。这也会将所有保存执行为atomic transaction