ruby-on-rails-4 - 为什么当我在 rails 4 数据库中使用载波上传图像时会回滚?

标签 ruby-on-rails-4 carrierwave strong-parameters

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

如果我不选择要上传的图像而仅发送字符串,则一切正常,但如果我发送图像文件,则会出现如下错误:

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

我的 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

请告诉我什么时候我错了?之前谢谢

最佳答案

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

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

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

(有关更多详细信息,请参阅 docs)

关于ruby-on-rails-4 - 为什么当我在 rails 4 数据库中使用载波上传图像时会回滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20962956/

相关文章:

ruby-on-rails - 强参数中嵌套对象中的Rails 4嵌套数组

ruby-on-rails - Carrierwave无法删除图像

ruby-on-rails - 如何在Rails 3.1中以单一形式创建多个对象?

ruby-on-rails - 转PG!数据库迁移错误:PG::ConnectionBad:

ruby-on-rails - 如何使用不同的名称为同一个模型创建两个关系?

ruby-on-rails-3 - Rails Carrierwave if ( :medium). 存在?

ruby-on-rails - rails : Photo uploads (Paperclip) with nesting & strong params

ruby-on-rails - 使用强大的参数自定义设计

ruby-on-rails - 验证 Rails 4 中的电话号码格式 - REGEX

ruby-on-rails-4 - 使用 Bundler 和 Rails 4 从生产中删除开发 gem