【问题标题】:Iterating Over Params Hash迭代参数哈希
【发布时间】:2011-02-28 07:43:33
【问题描述】:

上传一些图片让我非常沮丧。它们显然是作为机架/多部分上传的,但我迭代参数哈希的方式一定会导致问题。我真的需要一些帮助,这样我就可以停止拔头发了。

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

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

我似乎无法访问图片数据本身,但可以继续访问某些字符串。但这不是文件名,而是一些带有转义字符的奇怪东西。如何访问实际数据?

【问题讨论】:

  • 那么你遇到了什么问题?
  • 很抱歉没有真正说明我的问题!我已经在帖子底部提出了我的问题。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多