0

我有一个错误:

PrintsController 中的类型错误#update

无法将字符串转换为整数

我使用的表单代码是:

<%= 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

我的黑白模型也具有“序列化”功能,以便将数字数组存储到数据库中:

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
4

1 回答 1

0

空字符串可能是选择的默认值。您可以通过确保 :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/

于 2013-05-31T13:58:58.340 回答