Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why when i'm upload image using carrierwave in rails 4 database is rollback?

i try to save image file using carrierwave in rails 4, but when submit button is click database is rollback??? why ?

if i dont select image to upload and just send string only, all work properly but if i send image file i get error like this :

TypeError: can't cast ActionDispatch::Http::UploadedFile to string: INSERT INTO "items" ("created_at", "description", "image", "name", "store_id", "sub_items", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)
   (0.2ms)  rollback transaction
*** ActiveRecord::StatementInvalid Exception: TypeError: can't cast ActionDispatch::Http::UploadedFile to string: INSERT INTO "items" ("created_at", "description", "image", "name", "store_id", "sub_items", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)

my view :

<%= form_for @items, :url => dashboard_create_items_path(@store.id), :html => {:multipart => true} do |f| %>
  <%= f.label :name, 'Name' %>
  <%= f.text_field :name %><br />
  <%= f.label :title, 'Title' %>
  <%= f.text_field :title %><br />
  <%= f.label :image, 'Image' %>
   <%= f.file_field :image %><br />
  <%= f.label :description, 'Description' %>
  <%= f.text_field :description %><br />
  <%= f.label :sub_items %><br>
  <%= f.select :sub_items, options_for_select([["true", true], ["false", false]]), :selected => 'true' %><br />
  <%= f.submit %>
<% end %>

my controller :

def create_items    
    store = Store.find(params[:id])
    @items = store.items.create(item_params)

    if @items
      redirect_to dashboard_show_items_url(@items.id, store.id)
    else
      redirect_to dashboard_new_items_url
    end
  end

private

    def item_params
      params.require(:item).permit(:name, :title, :image, :description, :sub_items, :store_id)
    end

please tell me when i'm wrong? thanks before

like image 619
tardjo Avatar asked Dec 19 '22 19:12

tardjo


1 Answers

You may be seeing this error message because Carrierwave hasn't been initialized in your model.

The carrierwave method mount_uploader needs to be added to the image field in the model like this:

class Item < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

(see the docs for more details)

like image 88
benjaminjosephw Avatar answered Apr 08 '23 23:04

benjaminjosephw