Ошибка Rails 3.1 CarrierWave

Я следовал руководству http://railscasts.com/episodes/253-carrierwave-file-uploads?view=asciicast, и у меня есть настройка вложенной формы с прикрепленной внутри вложенной формы ниже. Все работает нормально, но изображение не загружается/сохраняет имя файла в БД.

<%= simple_nested_form_for(@order) do |f| %>
  <%= f.error_notification %>

  <div class="inputs">
        <label> <%= link_to 'New Customer', new_customer_path %> <small>or</small></label><div class="clear"></div>
        <%= f.association :customer, :label =>'Existing Customer', :include_blank => false %>
        <%= f.input :due_date, :as => :date, :start_year => Date.today.year, :start_day => Date.today.day, :stary_month => Date.today.month, :order => [:month, :day, :year], :input_html => { :class => 'date' }  %>
        <%= f.input :sales_tax, :input_html => { :class => 'text', :value => current_user.sales_tax, :onChange=>"itemcalculate()", :id => 'invoice-salestax' }, :hint => '%'  %>
        <%= f.input :discount, :input_html => { :class => 'text', :onChange=>"itemcalculate()", :id => 'invoice-discount' }, :placeholder => '$30', :label => 'Discount'  %>

            <%= f.fields_for :lineitems do |item| %>
                <div id='size'>
                <label style="margin-top:0 !important;">Details</label>
                <%= item.input :product_name, :input_html => { :class => 'text' }, :label => false, :wrapper_html => { :class => 'detail-wrapper' }, :input_html => { :class => 'details'}, :hint => 'Product Name', :placeholder => 'Gildan 2000'  %>
                <%= item.input :color, :input_html => { :class => 'text' }, :label => false, :wrapper_html => { :class => 'detail-wrapper' }, :input_html => { :class => 'details'}, :hint => 'Product Color', :placeholder => 'Blue'  %>
                <%= item.input :price_per, :input_html => { :class => 'text details', :onChange=>"itemcalculate()", :id => 'invoice-priceper' }, :label => false, :wrapper_html => { :class => 'detail-wrapper' }, :hint => 'Price per', :placeholder => "4.50", :required => true  %>
                <%= item.input :extra_fee, :input_html => { :class => 'text details', :onChange=>"itemcalculate()", :id => 'invoice-extrafee' }, :label => false, :wrapper_html => { :class => 'detail-wrapper', :value => '0' }, :hint => 'Extra fee', :required => true  %>
            <div class='clear'></div>
                <label>Sizes</label>                
                <%= item.input :xxs, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-xxs' },  :hint=> 'xxs', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>
                <%= item.input :xs, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-xs' },  :hint=> 'xs', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>
                <%= item.input :s, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-s' },  :hint=> 's' , :label => false, :wrapper_html => { :class => 'size-wrapper' }%>
                <%= item.input :m, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-m' },  :hint=> 'm', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>
                <%= item.input :l, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-l' },  :hint=> 'l', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>
                <%= item.input :xl, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-xl' },  :hint=> 'xl', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>
                <%= item.input :xxl, :input_html => { :class => 'sizes', :value => '0', :onChange=>"itemcalculate()", :id => 'invoice-xxl' },  :hint=> 'xxl', :label => false, :wrapper_html => { :class => 'size-wrapper' } %>

                <label>Extra Notes</label>
                <%= item.text_area :extra_notes %>

                <!-- start image upload -->
                    <%= item.fields_for :images, :html => {:multipart => true} do |image| %>
                    <%= f.file_field :image %>
                    <%= image.link_to_remove "Remove Image", :id => 'remove-image' %>
                    <% end %>
                    <%= item.link_to_add "<img src='/images/icon-camera.png' id='camera-icon'/> Add an image".html_safe, :images, :id=> 'add-image'  %>
                <!-- end image upload -->

                <div class='clear'></div>
                <%= item.link_to_remove "Remove Item" %>

                </div>
            <% end %>

            <p id='add-new-item'><%= f.link_to_add "+ Add an Item", :lineitems  %></p>
            </div>
            <%= f.hidden_field :user_id, :value => current_user.id %>
  <div class="actions">
    <%= f.button :submit %>
  </div>
<% end %>

Я получаю сообщение об ошибке WARNING: Can't mass-assign protected attributes: image WARNING: Can't mass-assign protected attributes: images_attributes

Моя модель изображения выглядит так:

class Image < ActiveRecord::Base
  attr_accessible :lineitem_id, :image
  belongs_to :lineitem, :polymorphic => true
  mount_uploader :image, ImageUploader

end
# == Schema Information
#
# Table name: images
#
#  id          :integer         not null, primary key
#  lineitem_id :integer
#  image       :string(255)
#  created_at  :datetime
#  updated_at  :datetime
#

Есть идеи, что случилось?


person bcackerman    schedule 16.02.2012    source источник


Ответы (4)


в разделе загрузки изображений, я думаю, вы хотите

<%= image.file_field :image %>

вместо

<%= f.file_field :image %>

звучит/похоже, что вы пытаетесь прикрепить поле файла изображения к форме заказов, когда оно должно быть частью вложенной формы, которую вы создали для изображения.

person mikeb    schedule 04.03.2012

Я предполагаю, что эта строка:

attr_accessible :lineitem_id, :image

предотвращает сохранение вашего изображения. Вам следует исправить/улучшить это определение, чтобы оно принимало и другие параметры при массовом назначении.

person socjopata    schedule 16.02.2012
comment
Но какие еще параметры он мог принять? Это единственные два поля, кроме id/createdby/updatedat. - person bcackerman; 16.02.2012
comment
Имхо, у вас в сообщении об ошибке явно написано - images_attributes. Если вы не уверены, вы всегда можете указать параметры броска в действии создания контроллера, чтобы увидеть, что там есть, или записать это. - person socjopata; 17.02.2012
comment
Я добавил images_attributes в Lineitem attr_accessible, и эта ошибка исчезла, но с ошибкой image все равно не повезло... есть предложения? Добавление image тоже ничего не дает. - person bcackerman; 17.02.2012
comment
Я думаю, вам не хватает :multipart =› истинного определения для вашей формы. Вы можете обратиться к документам. - person socjopata; 19.02.2012
comment
Хм, у меня это вверху pastie.org/3415104, и я также пытался поместить его в изображение вложенная форма, но все та же ошибка атрибута WARNING: Can't mass-assign protected attributes: image - person bcackerman; 19.02.2012
comment
На этом этапе вы должны знать, что означает эта ошибка массового назначения. Интересно, правильно ли вы настроили Carrierwave. - person socjopata; 20.02.2012

используйте что-то вроде этого, так как я не использую активную запись, некоторые вещи отсутствуют ... но вы должны быть в состоянии адаптировать ее к своим потребностям.

class LineItem

  attr_accessible :images_attributes
  has_many :images

  accepts_nested_attributes_for :images, :allow_destroy => true
end

class Image
  attr_accessible :lineitem_id, :image
  belongs_to :lineitem, :polymorphic => true
  mount_uploader :image, ImageUploader
end

это должно работать

person Orlando    schedule 02.04.2012

Вам нужно добавить :remove_image в attr_accessible.

person smoothdvd    schedule 13.07.2012