首页 \ 问答 \ Rails Paper Clip上传不起作用...没有错误抛出,回滚事务(Rails Paper Clip upload not working… No error thrown, rolls back transaction)

Rails Paper Clip上传不起作用...没有错误抛出,回滚事务(Rails Paper Clip upload not working… No error thrown, rolls back transaction)

编辑:我设法让它开始抛出错误,通过改变模型到这个:

class User < ApplicationRecord
    has_secure_password

    has_attached_file :avatar, 
        :path => ":rails_root/public/system/:attachment/:id/:basename_:style.:extension",
        :url => "/system/:attachment/:id/:basename_:style.:extension",
        :styles => {
          :thumb    => ['100x100#',  :jpg, :quality => 70],
          :preview  => ['480x480#',  :jpg, :quality => 70],
          :large    => ['600>',      :jpg, :quality => 70],
          :retina   => ['1200>',     :jpg, :quality => 30]
        },
        :convert_options => {
          :thumb    => '-set colorspace sRGB -strip',
          :preview  => '-set colorspace sRGB -strip',
          :large    => '-set colorspace sRGB -strip',
          :retina   => '-set colorspace sRGB -strip -sharpen 0x0.5'
        }

    validates_attachment :avatar,
        :presence => true,
        :size => { :in => 0..10.megabytes },
        :content_type => { :content_type => /^image\/(jpeg|png|gif|tiff)$/ }

    belongs_to :leitung
    def admin?
        self.role == "Admin"
    end
    def al?
        self.role == "Al"
    end
end

控制台现在看起来像这样:

Started POST "/leiter/new" for 127.0.0.1 at 2017-01-01 17:11:59 +0000
Processing by Leiter::UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"2z3H8rWo2TLADJtx3kWiCufulyLSBzLLCrxLGaLFH9BWOlGtMZ7BuPFCte8cEY5fC6yFVVggbi6vhESWLFFlRA==", "user"=>{"first_name"=>"asdf", "last_name"=>"asdf", "pfadi_name"=>"asdf", "email"=>"asdf@asdf.asdf", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "leitung_id"=>"1", "role"=>"asdf", "avatar"=>#<ActionDispatch::Http::UploadedFile:0x007feb301d8058 @tempfile=#<Tempfile:/tmp/RackMultipart20170101-6509-1yifkdk.jpg>, @original_filename="nobody_m.original.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"nobody_m.original.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create an account"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
Command :: file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-tn2f1u.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
   (0.1ms)  begin transaction
Command :: file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-1p20xan.jpg'
  Leitung Load (0.2ms)  SELECT  "leitungen".* FROM "leitungen" WHERE "leitungen"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.0ms)  rollback transaction
Redirected to http://localhost:3000/leiter/new
Completed 302 Found in 136ms (ActiveRecord: 0.4ms)

但是,对这个问题的常见解决方法是将development.rb文件设置为这个不起作用:

Paperclip.options[:command_path] = "/usr/local/bin/"

(开始的OP :)我正在设置回形针(与ImageMagick),以便我的应用程序上的用户可以上传他们的帐户的头像。 头像应该保存在本地服务器上(说我的电脑,因为应用程序目前正在开发中)。 我按照GitHub上的文档来设置回形针。 一切似乎都在努力......直到我尝试实际上传图像。 提交后(在这种情况下,编辑现有用户添加图像,但同样的事情发生在创建新用户时),它不会抛出错误或任何东西,它只是重新加载页面并灰色提交按钮。 以下消息出现在控制台中:

    Started PUT "/leiter/edit" for 127.0.0.1 at 2016-12-31 18:33:19 +0000
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Leiter::UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"RjjDgMQESgZ/9DVXTWoTvJDitAmYXqfMyVJJyKpXDsp3hE0dejJ6erMlV+wsFEH9bFlz7ZsvBlgPO63o8PkpYw==", "user"=>{"first_name"=>"Admin", "last_name"=>"Admin", "pfadi_name"=>"Admin", "email"=>"admin@application.com", "leitung_id"=>"6", "role"=>"Admin", "avatar"=>#<ActionDispatch::Http::UploadedFile:0x00000003671238 @tempfile=#<Tempfile:/tmp/RackMultipart20161231-3455-mekx7p.jpg>, @original_filename="nobody_m.original.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"nobody_m.original.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Speichern"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  begin transaction
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20161231-3455-1vvcs8q.jpg'
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20161231-3455-1cldo2f.jpg'
  Leitung Load (0.2ms)  SELECT  "leitungen".* FROM "leitungen" WHERE "leitungen"."id" = ? LIMIT ?  [["id", 6], ["LIMIT", 1]]
   (0.1ms)  rollback transaction
No template found for Leiter::UsersController#update, rendering head :no_content
Completed 204 No Content in 81ms (ActiveRecord: 1.4ms)

在视图中,图像应该出现的任何位置,它表示丢失。 有趣的是,如果我不上传图片,它可以让我创建和更新用户,即使我有参数中需要的图片。 至于为什么会发生这种情况,我绝对无能为力。 如果有帮助,这里是我的用户模型,我的控制器等:

用户模型:

class User < ApplicationRecord
    has_secure_password
    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
    validates_attachment_content_type :avatar, :content_type => ["avatar/jpg", "avatar/jpeg", "avatar/png", "avatar/gif"]
    belongs_to :leitung
    def admin?
        self.role == "Admin"
    end
    def al?
        self.role == "Al"
    end
end

用户控制器:

class Leiter::UsersController < ApplicationController
    def new
        @newuser = User.new
    end
    def edit
        @user = User.find(session[:user_id])
    end
    def update
        @user = User.find(session[:user_id])
        if @user.update_attributes(user_params) then
            redirect_to '/leiter'
        end
    end
    def create 
      @user = User.new(user_params) 
      if @user.save 
        redirect_to '/leiter'
      else 
        redirect_to '/' 
      end 
    end

    private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :pfadi_name, :email, :password, :password_confirmation, :leitung_id, :role, :avatar)
    end
end

查看更新用户:

<%= simple_form_for @user, url: {action: "edit"}, html: { method: :put } do |f| %>
    <%= f.text_field :first_name, :placeholder => "First name" %><br>
    <%= f.text_field :last_name, :placeholder => "Last name" %><br>
    <%= f.text_field :pfadi_name, :placeholder => "Pfadi name" %><br>
    <%= f.email_field :email, :placeholder => "Email" %><br>
    <%= f.association :leitung, :placeholder => "Leitung" %><br>
    <%= f.text_field :role, :placeholder => "Rolle" %><br>
    <%= f.input :avatar, as: :file %>
    <%= f.submit "Speichern", class: "btn-submit" %>
<% end %>

如果您需要更多信息,我可以提供。 感谢您的帮助,我确信我犯了一些小错误,但我找不到它......我是新手,但迄今为止它非常有趣!

编辑:

gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
gem "paperclip", "~> 5.0.0"
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

EDIT: I've managed to get it to start throwing errors by changing the model to this:

class User < ApplicationRecord
    has_secure_password

    has_attached_file :avatar, 
        :path => ":rails_root/public/system/:attachment/:id/:basename_:style.:extension",
        :url => "/system/:attachment/:id/:basename_:style.:extension",
        :styles => {
          :thumb    => ['100x100#',  :jpg, :quality => 70],
          :preview  => ['480x480#',  :jpg, :quality => 70],
          :large    => ['600>',      :jpg, :quality => 70],
          :retina   => ['1200>',     :jpg, :quality => 30]
        },
        :convert_options => {
          :thumb    => '-set colorspace sRGB -strip',
          :preview  => '-set colorspace sRGB -strip',
          :large    => '-set colorspace sRGB -strip',
          :retina   => '-set colorspace sRGB -strip -sharpen 0x0.5'
        }

    validates_attachment :avatar,
        :presence => true,
        :size => { :in => 0..10.megabytes },
        :content_type => { :content_type => /^image\/(jpeg|png|gif|tiff)$/ }

    belongs_to :leitung
    def admin?
        self.role == "Admin"
    end
    def al?
        self.role == "Al"
    end
end

Console now looks like this:

Started POST "/leiter/new" for 127.0.0.1 at 2017-01-01 17:11:59 +0000
Processing by Leiter::UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"2z3H8rWo2TLADJtx3kWiCufulyLSBzLLCrxLGaLFH9BWOlGtMZ7BuPFCte8cEY5fC6yFVVggbi6vhESWLFFlRA==", "user"=>{"first_name"=>"asdf", "last_name"=>"asdf", "pfadi_name"=>"asdf", "email"=>"asdf@asdf.asdf", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "leitung_id"=>"1", "role"=>"asdf", "avatar"=>#<ActionDispatch::Http::UploadedFile:0x007feb301d8058 @tempfile=#<Tempfile:/tmp/RackMultipart20170101-6509-1yifkdk.jpg>, @original_filename="nobody_m.original.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"nobody_m.original.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create an account"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
Command :: file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-tn2f1u.jpg'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-q2rz7h.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
   (0.1ms)  begin transaction
Command :: file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20170101-6509-1p20xan.jpg'
  Leitung Load (0.2ms)  SELECT  "leitungen".* FROM "leitungen" WHERE "leitungen"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.0ms)  rollback transaction
Redirected to http://localhost:3000/leiter/new
Completed 302 Found in 136ms (ActiveRecord: 0.4ms)

However, the usual fix to this problem, setting the development.rb file to this didn't work:

Paperclip.options[:command_path] = "/usr/local/bin/"

(Start of OP:) I'm working on setting up paperclip (with ImageMagick) so that users on my app can upload avatars for their account. The avatars should be saved locally on the server (speak my PC as the app is in development only at the moment). I followed the documentation on GitHub to set up paperclip. Everything seems to be working... Right until I try to actually upload an image. After I submit (in this case editing an existing user to add an image, but the same thing happens when creating a new user), it doesn't throw an error or anything, it just reloads the page and grays out the submit button. The following message appears in the console:

    Started PUT "/leiter/edit" for 127.0.0.1 at 2016-12-31 18:33:19 +0000
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Leiter::UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"RjjDgMQESgZ/9DVXTWoTvJDitAmYXqfMyVJJyKpXDsp3hE0dejJ6erMlV+wsFEH9bFlz7ZsvBlgPO63o8PkpYw==", "user"=>{"first_name"=>"Admin", "last_name"=>"Admin", "pfadi_name"=>"Admin", "email"=>"admin@application.com", "leitung_id"=>"6", "role"=>"Admin", "avatar"=>#<ActionDispatch::Http::UploadedFile:0x00000003671238 @tempfile=#<Tempfile:/tmp/RackMultipart20161231-3455-mekx7p.jpg>, @original_filename="nobody_m.original.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"nobody_m.original.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Speichern"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  begin transaction
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20161231-3455-1vvcs8q.jpg'
Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/tmp/3068f4f020f8c43d300b1e06b58b829b20161231-3455-1cldo2f.jpg'
  Leitung Load (0.2ms)  SELECT  "leitungen".* FROM "leitungen" WHERE "leitungen"."id" = ? LIMIT ?  [["id", 6], ["LIMIT", 1]]
   (0.1ms)  rollback transaction
No template found for Leiter::UsersController#update, rendering head :no_content
Completed 204 No Content in 81ms (ActiveRecord: 1.4ms)

In the views, anywhere the image is supposed to appear, it says missing instead. Interesting is that it lets me create and update users if I don't upload an image, even though I have the image required in the parameters. I am absolutely clueless as to why this happens. If it helps, here are is my user model, my controllers etc.:

User Model:

class User < ApplicationRecord
    has_secure_password
    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
    validates_attachment_content_type :avatar, :content_type => ["avatar/jpg", "avatar/jpeg", "avatar/png", "avatar/gif"]
    belongs_to :leitung
    def admin?
        self.role == "Admin"
    end
    def al?
        self.role == "Al"
    end
end

Users Controller:

class Leiter::UsersController < ApplicationController
    def new
        @newuser = User.new
    end
    def edit
        @user = User.find(session[:user_id])
    end
    def update
        @user = User.find(session[:user_id])
        if @user.update_attributes(user_params) then
            redirect_to '/leiter'
        end
    end
    def create 
      @user = User.new(user_params) 
      if @user.save 
        redirect_to '/leiter'
      else 
        redirect_to '/' 
      end 
    end

    private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :pfadi_name, :email, :password, :password_confirmation, :leitung_id, :role, :avatar)
    end
end

View to update user:

<%= simple_form_for @user, url: {action: "edit"}, html: { method: :put } do |f| %>
    <%= f.text_field :first_name, :placeholder => "First name" %><br>
    <%= f.text_field :last_name, :placeholder => "Last name" %><br>
    <%= f.text_field :pfadi_name, :placeholder => "Pfadi name" %><br>
    <%= f.email_field :email, :placeholder => "Email" %><br>
    <%= f.association :leitung, :placeholder => "Leitung" %><br>
    <%= f.text_field :role, :placeholder => "Rolle" %><br>
    <%= f.input :avatar, as: :file %>
    <%= f.submit "Speichern", class: "btn-submit" %>
<% end %>

If you need additional information, I can provide it. Thank you for helping, I'm sure I've made some trivial mistake, but I can't find it... I'm new to rails, but its been very fun so far!

EDIT:

gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
gem "paperclip", "~> 5.0.0"
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

原文:https://stackoverflow.com/questions/41410923
更新时间:2022-11-13 22:11

最满意答案

可以使用UNION ALL收集所有可能的值,然后COUNT(DISTINCT bag)将完成其余的操作,如下所示:

SELECT COUNT(DISTINCT bag) from (SELECT bag_1 AS bag FROM demo UNION ALL SELECT bag_2 AS bag FROM demo) a;

+---------------------+ | count(distinct bag) | +---------------------+ | 7 | +---------------------+

编辑:@Tim Biegeleisen和@eggyal的屈膝礼,一个较短的形式是:

SELECT COUNT(*) from (SELECT bag_1 AS bag FROM demo UNION SELECT bag_2 AS bag FROM demo) a;


One can use UNION ALL to collect all possible values, then COUNT(DISTINCT bag) will do the rest, like so:

SELECT COUNT(DISTINCT bag) from (SELECT bag_1 AS bag FROM demo UNION ALL SELECT bag_2 AS bag FROM demo) a;

+---------------------+ | count(distinct bag) | +---------------------+ | 7 | +---------------------+

Edit: curtsy of @Tim Biegeleisen and @eggyal, a shorter form would be:

SELECT COUNT(*) from (SELECT bag_1 AS bag FROM demo UNION SELECT bag_2 AS bag FROM demo) a;

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)