首页 \ 问答 \ Rails 5 CarrierWave错误“nil不是有效的资产来源”(Rails 5 CarrierWave error “nil is not a valid asset source”)

Rails 5 CarrierWave错误“nil不是有效的资产来源”(Rails 5 CarrierWave error “nil is not a valid asset source”)

当我到达我的应用程序中的显示页面时,我收到错误“nil不是有效的资产来源”。 我不确定如果图像只是没有保存或我试图显示它是错误的。

上传文件夹:

class AvatarUploader < CarrierWave::Uploader::Base

storage :file

 def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
 end

档案型号:

class Profile < ApplicationRecord

  has_many :albums

  mount_uploader :image, AvatarUploader
end

架构:

 create_table "profiles", force: :cascade do |t|
  t.string   "name"
  t.date     "born"
  t.string   "bio"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string   "image"
 end

图片上传的视图字段:

class ProfilesController < ApplicationController
 before_action :set_profile, only: [:show, :edit, :update, :destroy]

 def index
  @search = Profile.search(params[:q])
  @profiles = @search.result(distinct: true)
 end

 def show
 end

 def new
  @profile = Profile.new
 end

 def edit
 end

 def create
  @profile = Profile.new(profile_params)

  respond_to do |format|
  if @profile.save format.html { redirect_to @profile, notice: 'Profile was  successfully       created.' }
    format.json { render :show, status: :created, location: @profile }
   else
     format.html { render :new }
     format.json { render json: @profile.errors, status:  :unprocessable_entity }
    end
  end
end

def update
 respond_to do |format|
  if @profile.update(profile_params)
    format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
    format.json { render :show, status: :ok, location: @profile }
   else
    format.html { render :edit }
    format.json { render json: @profile.errors, status: :unprocessable_entity }
    end
   end
  end

 def destroy
  @profile.destroy
 respond_to do |format|
  format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' }
  format.json { head :no_content }
  end
end

private

def set_profile
  @profile = Profile.find(params[:id])
end

 def profile_params
  params.require(:profile).permit(:name, :bio, :born)
 end    
end

我填写的表单视图并添加图片和信息:

<%= form_for @profile, :html => {:multipart => true} do |f| %>
<% if @profile.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@profile.errors.count, "error") %> prohibited this profile from being saved:</h2>
  <ul>
  <% @profile.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
 </div>
 <% end %>

<div class="field">
 <%= f.file_field :image %><br>
</div>

<div class="field">
 <%= f.label :name %><br>
 <%= f.text_field :name %>
</div>
<br>
<div class="field">
<%= f.label :bio %><br>
<%= f.text_area :bio %>
</div>
<br>
<div class="field">
<%= f.label :born %><br>
<%= f.date_select :born %>
</div>
<br>
<div class="actions">
<%= f.submit %>

在Show视图中我收到错误:

<p>
<%= image_tag @profile.image_url %>
</p>

<p>
<strong>Name:</strong>
<%= @profile.name %>
</p>

<p>
<strong>Bio:</strong>
<%= @profile.bio %>
</p>

<p>
<strong>Born:</strong>
<%= @profile.born %>
</p>

<%= link_to 'Edit', edit_profile_path(@profile) %> |
<%= link_to 'Back', profiles_path %>

我提交图像并获得错误消息,其中突出显示了上面的显示视图中的行。

“显示/home/ubuntu/workspace/music-db/app/views/profiles/show.html.erb,其中第5行引发:

nil不是有效的资产来源“

从阅读其他类似的问题。 我们可能是图像没有正确保存。 好像有图像保存它不会是零。 但我真的不确定。 我只是第一次尝试这个宝石。

非常感谢任何和所有的帮助。


Im getting an error "nil is not a valid asset source" when I got to the show page in my app. I'm not sure If it the image is just not saving or how I am attempting to display it is wrong.

Uploader folder:

class AvatarUploader < CarrierWave::Uploader::Base

storage :file

 def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
 end

Profile Model:

class Profile < ApplicationRecord

  has_many :albums

  mount_uploader :image, AvatarUploader
end

Schema:

 create_table "profiles", force: :cascade do |t|
  t.string   "name"
  t.date     "born"
  t.string   "bio"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string   "image"
 end

The Field from the View where the images gets uploaded:

class ProfilesController < ApplicationController
 before_action :set_profile, only: [:show, :edit, :update, :destroy]

 def index
  @search = Profile.search(params[:q])
  @profiles = @search.result(distinct: true)
 end

 def show
 end

 def new
  @profile = Profile.new
 end

 def edit
 end

 def create
  @profile = Profile.new(profile_params)

  respond_to do |format|
  if @profile.save format.html { redirect_to @profile, notice: 'Profile was  successfully       created.' }
    format.json { render :show, status: :created, location: @profile }
   else
     format.html { render :new }
     format.json { render json: @profile.errors, status:  :unprocessable_entity }
    end
  end
end

def update
 respond_to do |format|
  if @profile.update(profile_params)
    format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
    format.json { render :show, status: :ok, location: @profile }
   else
    format.html { render :edit }
    format.json { render json: @profile.errors, status: :unprocessable_entity }
    end
   end
  end

 def destroy
  @profile.destroy
 respond_to do |format|
  format.html { redirect_to profile_url, notice: 'Profile was successfully destroyed.' }
  format.json { head :no_content }
  end
end

private

def set_profile
  @profile = Profile.find(params[:id])
end

 def profile_params
  params.require(:profile).permit(:name, :bio, :born)
 end    
end

The Form View That I fill out and add the Picture and Info:

<%= form_for @profile, :html => {:multipart => true} do |f| %>
<% if @profile.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@profile.errors.count, "error") %> prohibited this profile from being saved:</h2>
  <ul>
  <% @profile.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
 </div>
 <% end %>

<div class="field">
 <%= f.file_field :image %><br>
</div>

<div class="field">
 <%= f.label :name %><br>
 <%= f.text_field :name %>
</div>
<br>
<div class="field">
<%= f.label :bio %><br>
<%= f.text_area :bio %>
</div>
<br>
<div class="field">
<%= f.label :born %><br>
<%= f.date_select :born %>
</div>
<br>
<div class="actions">
<%= f.submit %>

And the Show view where I get the error:

<p>
<%= image_tag @profile.image_url %>
</p>

<p>
<strong>Name:</strong>
<%= @profile.name %>
</p>

<p>
<strong>Bio:</strong>
<%= @profile.bio %>
</p>

<p>
<strong>Born:</strong>
<%= @profile.born %>
</p>

<%= link_to 'Edit', edit_profile_path(@profile) %> |
<%= link_to 'Back', profiles_path %>

I submit the image and get the error message with the line from the show view above highlighted.

"Showing /home/ubuntu/workspace/music-db/app/views/profiles/show.html.erb where line #5 raised:

nil is not a valid asset source"

From reading other similar issues. It us maybe that the image is not saving correctly. As if there was image save it would not be nil. But really I am just not sure. Am only trying out this gem for the first time.

Any and all help is greatly appreciated.


原文:https://stackoverflow.com/questions/40812453
更新时间:2019-12-03 09:45

最满意答案

将您的方法更改为accpet图像参数

 def profile_params
  params.require(:profile).permit(:name, :bio, :born)
 end

 def profile_params
  params.require(:profile).permit(:name, :bio, :born, :image)
 end

还要检查你应该安装gem 'mini_magick'


Change your method to accpet image param well

 def profile_params
  params.require(:profile).permit(:name, :bio, :born)
 end

to

 def profile_params
  params.require(:profile).permit(:name, :bio, :born, :image)
 end

As well check you should install gem 'mini_magick'

2016-11-26

相关问答

更多

添加多个日志文件(Adding multiple log files)

更改您的属性文件,如下所示。 fileAppender将添加到FOO logger和root logger中以记录所有消息。 FOOAppender将仅添加到FOO记录器中以仅记录其消息。 为记录器和appender提供不同的名称,有助于理解日志属性文件。 log4j.rootLogger = INFO,fileAppender log4j.logger.FOO=DEBUG,FOOAppender,fileAppender log4j.additivity.FOO=false log4j.a

为什么以下代码的输出“未找到”而不是“找到”?(Why below code's output is “not found” instead of “found”?)

在*x==y[i]您要比较两个字符的值而不是两个指针指向的数据。 请改用strcmp函数。 如果给定的两个指针指向的两个字符串相等,则返回0。 所以将它改为strcmp(x, y[i]) == 0 您还应该将char *y参数更改为char **y或char *y[]因为y是指向字符串的指针数组,而不仅仅是一个指针。 最后, compare(array, *numbers); 应该称为compare(array, numbers); 因为你想传递一个指向字符串数组的指针,而不只是一个指向一个字符

对R中某个字符后面的捕获数字的数学运算(Mathematical operation on captured number that comes after a certain character in R)

我们可以使用gsubfn进行乘法运算。 捕获数字,包括字符串末尾的小数( ([0-9.]+$) ),将其转换为数字并乘以60 library(gsubfn) gsubfn("([0-9.]+$)", ~ as.numeric(x)*60, x) #[1] "3434/73980" "3434.332/13932" "220.23/55973.4" "908.11111/540" 或者正确地遵循这些条件 gsubfn("\\/([0-9.]+$)", ~ paste0("/", as.

获取ORA-00918:列模糊定义:运行此SQL :(添加表时)(Getting ORA-00918: column ambiguously defined: running this SQL:(When adding a table))

如果具有相同列名的多个表,并且在没有别名的语句中使用此列名,则会出现此错误。 所以解释器无法确定它应该使用哪个表。 要修复查询,请检查所有没有别名的列,并为它们添加前缀。 (例如trx_number ) This errors appears when you have multiples table with same columns name and this column name is used in the statement without alias. So the interpr

仅从String中提取数字(Extract only the numbers from String)

更好的方法是使用String#replaceAll(regex, replacement)方法替换除数字之外的所有字符(如您所见,该方法需要使用正则表达式进行替换): String str = "12.123.123/1234-11"; String digits = str.replaceAll("\\D", ""); \\D匹配非数字字符。 相当于[^0-9] 。 请注意,您需要在Java正则表达式引擎上转义\D 如果您对使用Matcher#group()方法有限制,那么每次找到它们时都必

map迭代器不可递增(map iterator not incrementable)

错误的原因是我正在访问和修改neighbour[8] ,所以我正在修改out数组范围的元素,并且可能它已经对迭代器做了一些事情。 在Debug版本中,我得到了map/set iterator not incrementable错误,而在Release版本中,迭代器无法递增,导致程序无限循环。 The cause of the error was that I was accessing and modifying neighbour[8], so I was modifying element

如何在java中将Map 转换为Map ?(How to convert Map to Map in java?)

将属性添加到地图的最简洁方法是(从您的示例开始): for (String propName : properties.stringPropertyNames()) { map.put(propName, properties.getProperty(propName)); } 这在这种特殊情况下很有效,因为Properties对象实际上是一个包含String键和值的映射,因为getProperty方法很清楚。 由于可怕的向后兼容性原因Map<Object, Object>它仅被声明为

迁移到iText 7 - 将通用对象添加到PDF(Migrating to iText 7 - Adding generic object to PDF)

iText7确实默认情况下不会将未使用的对象写入输出文档。 至少有两种方法可以实现将悬空对象写入文档的用例。 选项1 使用PdfDocument#setFlushUnusedObjects方法始终刷新未使用的对象。 您拥有的其余代码是正确的并保持原样: pdfDocument.setFlushUnusedObjects(true); PdfLiteral obj = new PdfLiteral("HelloWorld"); PdfArray arr = new PdfArray(); arr

相关文章

更多

最新问答

更多
  • 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)
  • 分开foreach项目并单独打印(Separate foreach items and print them individually)
  • 写模式管道是否同步?(Is write mode pipe synchronous?)
  • 发现可用的Windows Phone强调色和本地化名称(Discover available Windows Phone accent colors and localized names)
  • 使用多线程和WPF更新集合(Update Collection with multithreading and WPF)
  • 如何在字符串的情况下使用同步?(How should the synchronization be used in case of strings?)
  • 打印唯一的行,比较不超过N个字符(Print unique lines, compare no more than N characters)
  • Javascript / jQuery - 如何调用switch case从另一个函数执行(Javascript/jQuery - how to call a switch case to execute from another function)
  • Hbase超时错误不断发生(Hbase timeout errors keep occuring)
  • 如何在Delphi中更改TabControl中活动TAB的颜色(How to change the color of active TAB in a TabControl, in Delphi)
  • 正则表达式:在sublime文本中替换一些PHP代码(Regex: replace some pieces of php code in sublime text)
  • 在带有Scene2D的LibGDX中,如何在按下按钮时连续向右走?(In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?)
  • 累加器如何在Haskell中工作?(How do accumulators work in Haskell?)
  • 使用开关检查市场和前缀与正确的货币符号(using switch to check market and prefix with correct currency symbol)
  • 在哪里分配一次使用类?(Where to allocate one time use class?)
  • 如何从两个DateTime / NaiveDateTime获取持续时间?(How do I get Duration from two DateTime / NaiveDateTime?)
  • 解析TimeSpan大于24小时?(Parse a TimeSpan greater than 24 hours? [duplicate])
  • 如何在球拍中本地更改阅读规则?(How to locally change reading rules in racket?)
  • 数据库应该由DI注入时的模拟存储(通过构造函数)(Mock storage when database should be injected by DI (through constructor))
  • 使用maven集成2个eclipse项目(Integrate 2 eclipse projects using maven)
  • 角度ng-repeat不检测变化(Angular ng-repeat not detecting changes)
  • Xaml组件在Silverlight + XNA应用程序的多个页面中可见(Xaml component visible in multiple pages in Silverlight+XNA applications)
  • 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)
  • 如何设计hyperledger链代码以适合您的业务?(how to design your chaincode of hyperledger to fit for your business?)
  • PHP readfile错误(PHP readfile error)
  • 在Date之后排序列表然后是时间(Sorting list after Date then time)
  • Android内部版本号(Android build number)
  • 在没有预设退出条件的情况下停止无限循环(stopping an infinite loop with no preset exit condition)
  • Phonegap应用程序全屏通过html页面中的按钮(Phonegap Application fullscreen through a button in html page)
  • PAA是否适合在门户网站中自动执行wcm库部署和设置?(Is PAA a good candidate for automating wcm library deployment and setup in portal?)