Rails4遍历嵌套的params哈希

时间:2014-02-20 19:04:56

标签: ruby-on-rails hash ruby-on-rails-4 nested-attributes

我正在尝试迭代嵌套哈希以访问两个单独的字段。这就是我想要做的事情:

  1. 检查:is_cover_photo是否为真
  2. 如果:is_cover_photo为真,那么我想在@point_of_interest上调用更新方法。
  3. 我不断收到错误,无法弄清楚如何完成此任务。

    这是我收到的错误:"no implicit conversion of Symbol into Integer"

    这是我的update point_of_interests_controller方法:

      def update
        @point_of_interest = PointOfInterest.find(params[:id])
    
        if @point_of_interest.update(params[:point_of_interest].permit(:title, :caption, :website, :summary, :latitude, :longitude, :cover_photo, albums_attributes: [:id, :cover_photo, :title, :is_cover_photo]))
          params[:point_of_interest][:albums_attributes].each do |key, value|
            value.each do |k, v|
              if k[:is_cover_photo] && k[:cover_photo].blank?
                @point_of_interest.update(:cover_photo => k[:cover_photo])
              end   
            end  
          end
          redirect_to @point_of_interest
        else
          render 'edit'
        end
        end
    

    以下是传递的参数:

    {"utf8"=>"✓",
     "_method"=>"patch",
     "authenticity_token"=>"XGvgfxFHZKpiE8eGqc+55qOlSSk9LYFGdywWyABezXo=",
     "point_of_interest"=>{"title"=>"WolfieOne",
     "latitude"=>"33.577836",
     "longitude"=>"-85.074692",
     "caption"=>"CaptionOne",
     "website"=>"google.com",
     "summary"=>"This is a test summary.",
     "albums_attributes"=>{"0"=>{"title"=>"Album Uno",
     "cover_photo"=>#<ActionDispatch::Http::UploadedFile:0x000000113ae4c0 @tempfile=#<Tempfile:C:/Users/Samuel/AppData/Local/Temp/RackMultipart20140220-7188-4ptfo1>,
     @original_filename="Lighthouse.jpg",
     @content_type="image/jpeg",
     @headers="Content-Disposition: form-data; name=\"point_of_interest[albums_attributes][0][cover_photo]\"; filename=\"Lighthouse.jpg\"\r\nContent-Type: image/jpeg\r\n">,
     "is_cover_photo"=>"1",
     "id"=>"23"},
     "1"=>{"title"=>"Album 2",
     "is_cover_photo"=>"0",
     "id"=>"24"},
     "2"=>{"title"=>"The Best Album Alive",
     "is_cover_photo"=>"0",
     "id"=>"30"}}},
     "commit"=>"Submit Wolfie",
     "id"=>"15"}
    

    对此的任何帮助将不胜感激。

    更新

    这解决了我的问题:感谢Coenwulf

    params[:point_of_interest][:albums_attributes].each do |key, value|
      if value[:is_cover_photo] && value[:cover_photo].present?
        @point_of_interest.update(:cover_photo => value[:cover_photo])
      end
    end
    

1 个答案:

答案 0 :(得分:0)

尝试用以下内容替换第一个if块的内容:

params[:point_of_interest][:albums_attributes].each do |key, value|
  if value[:is_cover_photo] && value[:cover_photo].present?
    @point_of_interest.update(:cover_photo => value[:cover_photo])
  end
end
redirect_to @point_of_interest

编辑:编辑使用礼物?而不是空白?根据OP的评论。