2016-05-27 140 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

我试过了,发布了上面的更新。 –