2014-02-20 53 views
0

我想通過嵌套哈希來訪問兩個單獨的字段。這就是我要做的:Rails4迭代通過嵌套參數哈希

  1. 檢查,看是否
  2. 如果:is_cover_photo是真的,那麼我想調用Update方法上@point_of_interest:is_cover_photo是真實的。

我不斷收到一個錯誤,不知道如何完成這個任務。

這是錯誤我得到:"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 
+0

什麼行會拋出錯誤? – tyler

+0

if k [:is_cover_photo] && k [:cover_photo] .blank? – EighthEmperor

+0

對不起,我忘了提及 – EighthEmperor

回答

0

嘗試,如果塊以代替第一的內容:

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的評論。

+0

這允許專輯的封面照片更新,但@ point_of_interest's:cover_photo未更新。任何想法爲什麼? – EighthEmperor

+0

你是否真的想要閱讀第二行:if value [:is_cover_photo] && value [:cover_photo] .present? – Coenwulf

+0

是的!對不起,我沒有正確理解.blank?工作。替換.blank?與.present?解決了我的問題。 – EighthEmperor