为什么当我在Rails 4数据库中使用载波上传图像时会回滚? [英] why when i'm upload image using carrierwave in rails 4 database is rollback?

查看:65
本文介绍了为什么当我在Rails 4数据库中使用载波上传图像时会回滚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在rails 4中使用载波保存图像文件,但是当提交按钮单击时,数据库回滚???为什么?

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 (?, ?, ?, ?, ?, ?, ?, ?)

我的观点:

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

我的控制器:

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

请告诉我我错了吗?

推荐答案

您可能会看到此错误消息,因为尚未在模型中初始化Carrierwave。

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

需要将载波方法 mount_uploader 添加到模型的图像字段中,如下所示:

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)

这篇关于为什么当我在Rails 4数据库中使用载波上传图像时会回滚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆