2016-05-27 138 views
0

我有下面的方法,我也得到了錯誤隱式轉換字符串到整數

上線「字符串的隱式轉換成整數」

if (!thisitem['value'].to_i.match(/[\/-].{2}/).nil?) 

小小背景:我是這個項目的新手,這是一個內部CMS。我試圖從Rails 2升級到Rails 4.我來自ASP.NET背景。

參數:參數:{ 「UTF8」=> 「✓」, 「authenticity_token」=> 「ahD3oriEXY895BNx53nd03Q6PQZ1yOQkgkpCGM4OlVqXODjrl3EIb6Uqa9mqVwwWgCQhV5qxRebCmEyoP57HzQ ==」, 「info_items」=> { 「1」=> { 「ID」=> 「1」,「description」=>「Billing Rate」, 「value」=>「110」},「2」=>「id」=>「2」,「description」=>「Travel Rate」 「值」=> 「55」}}, 「提交」=> 「更新」}

def update_info 
    @updated_items=params[:info_items] 
    @updated_items.each do |thisitem| 
     @item=TrackInformation.find_by_id(thisitem) 
     if (!thisitem['value'].match(/[\/-].{2}/).nil?) 
     thisdate=thisitem['value'] 
     if !thisdate.match(/\/.{2}/).nil? 
      newdate=Date.strptime(thisdate,"%m/%d/%Y") 
     else 
      newdate=Date.strptime(thisdate,"%m-%d-%Y") 
     end 
     thisdate=newdate 
     thisitem['value']=thisdate 
     end 
     @item.update_attributes(thisitem) 
     @item.changed_by=User.find(session[:user]).id 
     @item.save 
    end 

    end 

編輯:

所以讀@Anand我意識到,日期應該不等於價值,因爲價值是美元金額,所以我修改的方法是:

def update_info 
    i = 1 
    @updated_items=params[:info_items] 
    @updated_items.each do |this_item| 
     @item=TrackInformation.find_by_id(this_item[i][:id]) 
     @item.description = this_item[i][:description] 
     @item.value = this_item[i][:value] 
     @item.changed_by=session[:user].to_i 
     @item.save 
     i = i + 1 
    end 
    redirect_to :controller => 'admin', :action => 'list' 
    end 

現在,我得到:

未定義的方法`[]」爲零:NilClass

編輯2:

def update_info 
    byebug 
    @updated_items=params[:info_items] 
    @updated_items.each do |id, description, value| 
     @item=TrackInformation.find_by_id(id) 
     @item.value = value 
     @item.description = description 
     @item.changed_by=session[:user] 
     @item.save 
    end 
    redirect_to :controller => 'admin', :action => 'list' 
    end 

這似乎工作,但把這個在DB: enter image description here

編輯3:

def update_info 
    @updated_items=params[:info_items] 
    @updated_items.each do |this_item_key,this_item_value| 
     @item=TrackInformation.find_by_id(this_item_key) 

     @item.update_attribute(this_item_key, this_item_value) 
     @item.changed_by=session[:user] 
     @item.save 
    end 
    redirect_to :action => 'list' 
    end 

enter image description here

回答

1

根據您的參數,可以每thisitem是散列 - 你可以得到關鍵和值作爲塊參數,並適當地使用它們。此外,if !(something).nil?可簡化爲if something.present?。最後,這是一個好主意,用下劃線來命名變量 - 的this_item代替thisitem

更新:由於問題已經改變,更新下面還有

def update_info 
    @updated_items=params[:info_items] 
    @updated_items.each do |this_item_key,this_item_value| 
     @item=TrackInformation.find_by_id(this_item_key) 

     @item.value = this_item_value['value'] 
     @item.description = this_item_value['description'] 
     @item.changed_by=session[:user] 
     @item.save 
    end 

    end 
+0

的代碼我更新上述@Anand –

+1

嘗試信息用我的代碼替換你的代碼。當你需要獲得雙重鑰匙和價值時,你仍然在一個塊中獲得一個參數。 – Anand

+0

我試過了,發佈了上面的更新。 –