更新时无法将String转换为Integer

时间:2013-05-31 11:17:18

标签: ruby-on-rails

我遇到了错误:

  

PrintsController#update中的TypeError

     

无法将String转换为整数

我使用的表单代码是:

<%= form_for @print do |f| %>
....
....

<%= f.fields_for :blackwhites_attributes do |blackwhite| %>
<%= blackwhite.select :newpages , options_for_select((1..(@print.number_of_images_entry)).to_a), {}, :multiple => true, :size => @print.number_of_images_entry %>
<% end %>

在我的development.log中,我发现“newpages”选择字段中有一个空值。

>      Parameters: {"utf8"=>"✓", "authenticity_token"=>"xAs20vFEt3vEBOhFugOyR0nWIgkoMJ0d4JPbl5E5VQ4=",
> "print"=>{"quantity"=>"1", "blackwhites_attributes"=>{"newpages"=>["",
> "2", "3"]}, "comment"=>""}, "commit"=>"Update Print", "id"=>"5"}
>       User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1000 LIMIT 1
>       Print Load (0.3ms)  SELECT `prints`.* FROM `prints` WHERE `prints`.`id` = ? LIMIT 1  [["id", "5"]]
>       SQL (0.1ms)  BEGIN
>        (0.1ms)  ROLLBACK
>     Completed 500 Internal Server Error in 6ms

我的blackwhite模型也有“序列化”以存储到数据库中的数字数组:

class Blackwhite < ActiveRecord::Base
  attr_accessible :newpages, :print_id

  serialize :newpages

  belongs_to :print

end

但我发现问题是打印控制器更新没有构建表单而且我在Prints_controller中有构建

  def update
    @print = Print.find(params[:id])
    @print.blackwhites.build
      if @print.update_attributes(params[:print])
        redirect_to @print, :flash => { :success  => "Successfully updated your Print Order." }
      else
      render :action => 'edit'
      end
 end

打印模型:

    class Print < ActiveRecord::Base
      has_many :blackwhites
      belongs_to :user

      accepts_nested_attributes_for :blackwhites, :allow_destroy => true

      attr_accessible :comment, :document, :document_file_name,
                            :document_file_size, :document_updated_at, :is_printing,
                            :is_processing_image, :user_id, :document_content_type,
                            :number_of_images_entry, :is_delivered, :quantity, :blackwhites_attributes

...
...

      end

1 个答案:

答案 0 :(得分:0)

空字符串可能是select的默认值。您可以通过确保:include_blank和:prompt不设置为真实的东西来配置助手不使用助手。

另一个可能的解决方案是摆脱

attr_accessible :newpages

并将其替换为

def newpages
  self[:newpages].map(&:presence).compact
end

和/或

def newpages=(ary)
  self[:newpages] = ary.map(&:presence).compact
end

最后,更好的整体解决方案是使用FormObject模式而不是accepts_nested_attributes。然后,您可以完全控制模型的构建和持久性。请参阅此处的第3项:http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

相关问题