I am using CarrierWave with Rails 3.1. I am getting the following error message when I submit the form (trying to upload an image):
Error Message:
ActiveRecord::StatementInvalid in Admin::PostsController#create
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "posts" ("body", "created_at", "draft", "image", "post_type", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?)
Rails.root: /Users/aziz/Sandbox/ruby/rails/Tumblelog
Application Trace | Framework Trace | Full Trace
app/controllers/admin/posts_controller.rb:18:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"za+zNRDGNCcujnCmO726cWCo2ze1rgaXv5bL17JGaek=",
"post"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x000001014aeff0 #original_filename="AzizLight.jpeg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"post[image]\"; filename=\"AzizLight.jpeg\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/var/folders/ky/2ddtbt0d7k1g__2ctr8njcfc0000gn/T/RackMultipart20110918-21704-hp2ajt>>,
"draft"=>"0",
"user_id"=>"2",
"post_type"=>"image"},
"commit"=>"Post"}
The problem is that I don't know where this name comes from and I don't know what variable is being nil, so I can't debug properly (I tried to debug a log before asking here).
Line 18 corresponds to the #post.save line in the following controller:
PostsController:
# ...
def new
#post = Post.new
#form_html_options = (params[:post_type] == "image") ? { :multipart => true } : {}
#form_partial = get_form_partial(params[:post_type])
redirect_to admin_posts_path, :alert => "You tried to create an unknown type of post..." if #form_partial.nil?
#title = "Creating a new post..."
end
def create
#post = Post.new(params[:post])
if #post.save
flash[:success] = "Post created successfully!"
redirect_to admin_post_path(#post)
else
#title = "Creating a new post..."
#form_partial = get_form_partial(params[:post][:post_type])
render 'new'
end
end
# ...
Here other files that might be needed to spot the problem:
Post (model):
attr_accessible :title, :body, :user_id, :draft, :post_type, :image
belongs_to :user
mount_uploader :image_url, ImageUploader
ImageUploader:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :fog
def extension_white_list
%w(jpg jpeg gif png)
end
end
new.html.erb:
<h1><%= #title %></h1>
<%= form_for #post, :url => admin_posts_path, :html => #form_html_options do |f| %>
<%= render 'form', :f => f %>
<% end %>
_form.html.erb:
<%= render 'error_messages' %>
<%= render #form_partial, :f => f %>
<p class="drop-down">
<%= f.label :draft, 'Status' %>
<%= f.select(:draft, options_for_select([["Published", 0], ["Draft", 1]], (#post.new_record? ? 0: #post.draft))) %>
</p>
<%= f.hidden_field :user_id, :value => #post.user_id || current_user.id %>
<%= f.hidden_field :post_type, :value => #post.post_type || params[:post_type] %>
<p class="button"><%= f.submit "Post", :disable_with => 'Posting...' %></p>
_image_form.html.erb (#form_partial):
<p><%= f.file_field :image %></p>
So what it really going on please?
Your image uploader class was not loaded into your current rails server thread. Reload rails server and it should work fine =).
Make sure you use - mount_uploader :image, ImageUploader in your model like here -
class CarImage < ActiveRecord::Base
belongs_to :car
mount_uploader :image, ImageUploader
end
Regards
Robbie
I experienced the some problem and the cause is (probably always) that the UploadedFile object has been sent to the attribute carrierwave was mounted on. The db adapter cannot serialize this object and will therefore throw this error.
Make sure that:
the uploader has been properly mounted
you don't use write_attribute to write the uploaded file (which was the cause of my problem). Use the accessor instead: model.send('image=', params[:model][:image]). Uglier, but better.
Make sure in your model:
mount_uploader :image, ImageLoader
Remember that :image must be the string/text type.
I came across this post because I had the same error you described, but restarting the server didn't resolve it (as suggested by other answers). In my case, the problem was caused because I used mount_uploader before attr_accessible. By switching them I solved the problem.
I had a similar problem.
Solution was changing:
attr_accessible :title, :body, :user_id, :draft, :post_type, :image
belongs_to :user
mount_uploader :image_url, ImageUploader
to:
attr_accessible :title, :body, :user_id, :draft, :post_type, :image_url
belongs_to :user
mount_uploader :image_url, ImageUploader
Related
I can get the gallery attributes to insert as evident by server log below but picture attributes will not insert as well.
Server response
Started POST "/galleries" for 127.0.0.1 at 2017-05-13 18:19:23 +1000
Processing by GalleriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LACaMz44B9mn/psLYjzs8qrwo9mr0l2OEIPg+VmCn9CdbGhBh9rDUJ6FE0EOwKCj7aZVjbM4+t0YoaFIRX7IEA==", "gallery"=>{"name"=>"Hello", "cover"=>"123456", "picture"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xb943d50 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170513-2604-b2lnrz.jpg>, #original_filename="Skateboard 1.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[picture][picture]\"; filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Create Gallery"}
Unpermitted parameter: picture
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "galleries" ("name", "cover", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "Hello"], ["cover", 123456], ["created_at", 2017-05-13 08:19:23 UTC], ["updated_at", 2017-05-13 08:19:23 UTC]]
(65.1ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 74ms (ActiveRecord: 66.1ms)
Started GET "/" for 127.0.0.1 at 2017-05-13 18:19:23 +1000
....
GalleriesController
class GalleriesController < ApplicationController
def new
#gallery = Gallery.new
end
def create
#gallery = Gallery.new(gallery_params)
if #gallery.save
flash[:success] = "Picture created!"
redirect_to root_url
else
render 'new'
end
end
private
def gallery_params
params.require(:gallery).permit(:id, :name, :cover, pictures_attributes: [:id, :gallery_id, :picture, :_destroy])
end
end
_form.html.erb partial rendered from within new.html.erb
<%= form_for #gallery do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cover %>
<%= f.text_field :cover %>
</div>
<div id="pictures">
<%= f.fields_for #gallery.pictures do |pic| %>
<%= pic.file_field :picture %>
</div>
<% end %>
<div id="submit">
<%= f.submit %>
</div>
<% end %>
Models, Gallery
class Gallery < ApplicationRecord
has_many :pictures
validates :name, presence: true
validates :cover, presence: true
accepts_nested_attributes_for :pictures, allow_destroy: true
end
Picture
class Picture < ApplicationRecord
belongs_to :gallery
validates :gallery_id, presence: true
validates :picture, presence: true
mount_uploader :picture, PictureUploader
serialize :picture, JSON
end
Migrations, Gallery
class CreateGalleries < ActiveRecord::Migration[5.0]
def change
create_table :galleries do |t|
t.string :name
t.integer :cover
t.timestamps
end
end
end
Picture
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.integer :gallery_id
t.string :picture
t.timestamps
end
end
end
Unpermitted parameter: picture
The error is because your fields_for is wrong. The first parameter of fields_for should be a record_name(which should be :pictures in your case).
fields_for(record_name, record_object = nil, options = {}, &block)
You are passing record_object as a first parameter, which resulting in wrong params and leading to unpermitted error. Changing your code to below should resolve the issue.
<%= f.fields_for :pictures, #gallery.pictures do |pic| %>
<%= pic.file_field :picture %>
<% end %>
Judging by your parameters line here:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LACaMz44B9mn/psLYjzs8qrwo9mr0l2OEIPg+VmCn9CdbGhBh9rDUJ6FE0EOwKCj7aZVjbM4+t0YoaFIRX7IEA==",
"gallery"=>{"name"=>"Hello", "cover"=>"123456",
"picture"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xb943d50
#tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170513-2604-b2lnrz.jpg>,
#original_filename="Skateboard 1.jpg", #content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"gallery[picture][picture]\";
filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Create Gallery"}
and the fact you're getting the result: Unpermitted parameter: picture, you should change your strong parameters to
def gallery_params
params.require(:gallery).permit(:id, :name, :cover, picture: [:id, :gallery_id, :picture, :_destroy])
end
I got an error while setting up a polymorphic file upload with the paperclip gem on Ruby on Rails.
In the following, I will show you the relevant code parts.
I've set up a _form partial:
<%= form_for(#test_run, :html => { :multipart => true }) do |f| %>
<div class="row">
<div class="large-6 columns">
<%= fields_for :attachment do |attachment_fields| %>
<%= attachment_fields.file_field :attachment %><br />
<% end %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit t('buttons.general.save'), :class => "button slim", data: {disable_with: "#{t('buttons.general.disable')}"}, :alt => t('buttons.general.save'),:title => t('buttons.general.save') %>
</div>
</div>
My attachment model contains the file validation:
class Attachment < ActiveRecord::Base
belongs_to :attachable, :polymorphic => :true
has_attached_file :attachment
validates_attachment_content_type :attachment, content_type: /\A(image|application)\/.*\z/
end
In the attachment controller I whitelist the following parameters:
def attachment_params
params.require(:attachment).permit(:name, :user_id, :attachable_id, :attachable_type, :attachedfile)
end
The attachment should be attached to a test run. Here is the test run model:
class TestRun < ActiveRecord::Base
belongs_to :test_object
has_many :attachments, :as => :attachable
accepts_nested_attributes_for :attachments
end
The create method and the private methods of the test runs controller could be relevant, too:
def create
#test_run = TestRun.new(test_run_params)
attachment = Attachment.create(:attachable_id => #test_run_id, :attachment => params[:attachment])
render text: #test_run.attachments.first.inspect
end
private
# Use callbacks to share common setup or constraints between actions.
def set_test_run
#test_run = TestRun.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def test_run_params
params.require(:test_run).permit(:name, :test_object_id, :attachment, :start_time, :end_time, :test_demands, :allowed_bug_types, :max_testers, :test_language, :postprocessing_time, :test_standards, :target_tester, :target_devices)
end
To give you a completely overview, here is the attachment migration file:
class CreateAttachments < ActiveRecord::Migration
def change
create_table :attachments do |t|
t.string :name
t.integer :user_id
t.integer :attachable_id
t.string :attachable_type
t.timestamps null: false
end
end
end
Now, when I run this, fill out the form and select a valid file and submit the form after this, I receive the following error:
Paperclip::AdapterRegistry::NoHandlerError in TestRunsController#create
Ok, somehow, stackoverflow shrinks the error message, so I put it on pastebin.
If hope, someone of you could help me, as I am on this point since days of researching for bugs.
Thank you!
run migration:
rails generate paperclip attachment attachment
in your view:
<%= fields_for :attachment do |field| %>
<%= field.file_field :attachment %><br />
<% end %>
your attachment_params
def attachment_params
params.require(:attachment).permit(:name, :user_id, :attachable_id, :attachable_type, :attachment)
end
your method create
def create
#test_run = TestRun.new(test_run_params)
attachment = Attachment.create(attachment_params)
render text: #test_run.attachments.first.inspect
end
you must also included in this controller method attachment_params
I'm aware that there are several posts on Stackoverflow and several tutorials about this subject. None of them however manage to solve my issue and most of them are outdated as well.
I am trying to add multiple images to a project using the paperclip gem in Rails 4.
When i try uploading it i do see the asset attached in the params.
They do not seem to be added to the project_paramns though..
Hope someone can help me out here.
This is my projects_controller
class ProjectsController < ApplicationController
before_filter :find_project, only: [:show, :edit, :update, :destroy]
def index
#projects = Project.all
end
def show
end
def new
#project = Project.new
end
def create
#project = Project.new(project_params)
#project.save
redirect_to project_path(#project)
end
def edit
end
def update
#project.update(project_params)
redirect_to project_path(#project)
end
def destroy
#project.destroy
redirect_to projects_path
end
protected
def project_params
params.require(:project).permit(:name, :description, :asset)
end
def find_project
#project = Project.find(params[:id])
end
end
My project model
class Project < ActiveRecord::Base
has_many :assets, :dependent => :destroy
validates_associated :assets
validates_presence_of :name, :on => :create, :update => "can't be blank"
validates_presence_of :description, :on => :create, :update => "can't be blank"
accepts_nested_attributes_for :assets
end
My asset model
class Asset < ActiveRecord::Base
belongs_to :project
# Paperclip
has_attached_file :image,
:styles => {
:thumb=> "100x100#",
:small => "150x150>",
:medium => "300x300>",
:large => "400x400>" }
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end
And my form partial (Sorry it's in HAML)
= simple_form_for #project do |f|
%ul
- #project.errors.full_messages.each do |error|
%li= error
.row
.small-1.columns
= f.label :name, :class => "left inline"
.small-11.columns
= f.input_field :name
.row
.small-1.columns
= f.label :description, :class => "left inline"
.small-11.columns
= f.input_field :description, as: :text
.row
= f.simple_fields_for :asset do |a|
.small-1.columns
= a.label :image, :class => "left inline"
.small-11.columns
= file_field_tag :image, multiple: true,
.row
.small-9.small-offset-1.columns
= f.submit nil ,:class => "button [radius round]"
Request Parameters
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"4iK1kUNvKvoJVOKoivz/pcLAe6LY0cUJikQioxa8BIs=", "project"=>{"name"=>"adf", "description"=>"adf", "asset"=>{"image"=>[#<ActionDispatch::Http::UploadedFile:0x007fb808357d80 #tempfile=#<Tempfile:/var/folders/v_/98sxm8bn24qbqj_jmj40fv400000gn/T/RackMultipart20140607-34739-dvlzt7>, #original_filename="enabling-gzip-compression.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"project[asset][image][]\"; filename=\"enabling-gzip-compression.jpg\"\r\nContent-Type: image/jpeg\r\n">, #<ActionDispatch::Http::UploadedFile:0x007fb808357d58 #tempfile=#<Tempfile:/var/folders/v_/98sxm8bn24qbqj_jmj40fv400000gn/T/RackMultipart20140607-34739-lwkioi>, #original_filename="minimize_http_requests.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"project[asset][image][]\"; filename=\"minimize_http_requests.png\"\r\nContent-Type: image/png\r\n">]}}, "commit"=>"Update Project", "action"=>"update", "controller"=>"projects", "id"=>"11"}
Now i've also got an error showing up in my terminal:
Unpermitted parameters: asset
Edit:
A combination of #pavan's and #kiri thorat's answers have helped me get something showing up in project_params, the output it gives now is:
{"name"=>"Test", "description"=>"Test", "assets_attributes"=>{"0"=>{}}}
Any clue on what's going on here?
After #kirithorat's latest update things seem to be good on the parameter side of things.
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"4iK1kUNvKvoJVOKoivz/pcLAe6LY0cUJikQioxa8BIs=", "project"=>{"name"=>"Test", "description"=>"Test", "assets_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fcd383c9a08 #tempfile=#<Tempfile:/var/folders/v_/98sxm8bn24qbqj_jmj40fv400000gn/T/RackMultipart20140610-36517-7ek1oq>, #original_filename="enabling-gzip-compression.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"project[assets_attributes][0][image]\"; filename=\"enabling-gzip-compression.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}, "commit"=>"Update Project", "action"=>"update", "controller"=>"projects", "id"=>"13"}
The assets are still not being saved though.
Update after implementing #Valikiliy's suggestions
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"4iK1kUNvKvoJVOKoivz/pcLAe6LY0cUJikQioxa8BIs=", "project"=>{"name"=>"Test", "description"=>"Test", "image"=>#<ActionDispatch::Http::UploadedFile:0x007fcd3a08d0b8 #tempfile=#<Tempfile:/var/folders/v_/98sxm8bn24qbqj_jmj40fv400000gn/T/RackMultipart20140610-36517-rgy95n>, #original_filename="minimize_http_requests.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"project[image]\"; filename=\"minimize_http_requests.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Update Project", "action"=>"update", "controller"=>"projects", "id"=>"16"}
Update: Added new form code on request
= simple_form_for(#project, :html => { :multipart => true }) do |f|
%ul
- #project.errors.full_messages.each do |error|
%li= error
.row
.small-1.columns
= f.label :name, :class => "left inline"
.small-11.columns
= f.text_field :name
.row
.small-1.columns
= f.label :description, :class => "left inline"
.small-11.columns
= f.text_area :description
.row
= f.simple_fields_for :assets do |a|
.small-1.columns
= a.label :image, :class => "left inline"
.small-11.columns
- if a.object.new_record?
= a.input :image, as: :file
- else
= image_tag a.object.image.url(:thumb)
= a.input_field '_destroy', as: :boolean
.row
.small-9.small-offset-1.columns
= f.submit nil ,:class => "button [radius round]"
Update
def project_params
params.require(:project).permit(:name, :description, images: [], assets_attributes: [:_destroy, :id, :image])
end
def find_project
#project = Project.find(params[:id])
#project.assets.build if %w[new edit].include?(action_name)
end
Update: Added model code
class Project < ActiveRecord::Base
has_many :assets, :dependent => :destroy
validates_presence_of :name, :on => :create, :update => "can't be blank"
validates_presence_of :description, :on => :create, :update => "can't be blank"
accepts_nested_attributes_for :assets, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
To save multiple files in the above example you, do not need add multiple: true option, it will cause an error when saving, one file - one record assets table.
For resolve this, you can add multiple file fields, like this:
add into controller:
def new
#project = Project.new
3.times{ #project.assets.build }
end
def edit
3.times{ #project.assets.build }
end
for while list
.permit(..., assets_attributes: [ :_destroy, :id, :image ])
and in view like this:
= f.simple_fields_for :assets do |a|
.small-1.columns
= a.label :image, :class => "left inline"
- if a.object.new_record?
.small-11.columns
= a.file_field :image
- else
.small-11.columns
= image_tag a.object.image.url(:thumb)
= a.input_field '_destroy', as: :boolean
If you try to send multiple images like this:
# view
a.file_field :image, multiple: true
# controller
.permit(..., assets_attributes: [ :_destroy, :id, image: [] ])
This will cause an error because the Asset model does not know what to do with an array of images.
To save more than one file at the same time, you need to use your own handler, for example:
model: add the images= method
def images=(files = [])
assets.create(image: f)
end
controller: move images: [] outside of the assets_attributes
.permit(..., images: [], assets_attributes: [ :_destroy, :id ])
view: remove the fields_for and nested attributes
.row
.small-1.columns
=f.file_field :images, multiple: true
.row
= f.simple_fields_for :assets do |a|
.small-1.columns
= a.label :image, :class => "left inline"
....
You have 1-M relationship between Project and Asset models i.e.,
Project has_many assets
so, in your form partial simple_fields_for should look like
= f.simple_fields_for :assets do |a|
Notice assets in plural and NOT asset in singular
In your current code, you used simple_fields_for with singular asset which is why your params is generated incorrectly and you receive asset key in params hash instead of receiving assets_attributes key which results in the warning as Unpermitted parameters: asset.
Once you correct the form partial you would receive the correct keys in params hash upon form submission. Now, as #Pavan pointed out next problem that I see is you have not permitted the assets_attributes correctly in the controller.
You need to update the project_params method as below:
def project_params
params.require(:project).permit(:name, :description, assets_attributes: [:image])
end
Notice assets_attributes with assets in plural
UPDATE
You would need to add #project.assets.build in new and edit action of ProjectsController in order to see the fields for assets in the new and edit view.
Also, I would suggest adding :id in the list of permitted attributes for assets_attributes in project_params as below:
params.require(:project).permit(:name, :description, assets_attributes: [:id, :image])
Few more problems that I see is in the form partial are
As you are uploading a file, you should specify :html => {:multipart => true} in the form.
Change
= simple_form_for #project do |f|
To
= simple_form_for #project, :html => {:multipart => true} do |f|
Project has_many assets and every asset record would have only one image, so remove multiple: true. Also, as you are using simple_form, its advisable to use simple_form helper method for uploading file.
Change
= file_field_tag :image, multiple: true,
To
= a.input :image, as: :file
Your project_params should be like this
def project_params
params.require(:project).permit(:name, :description, assets_attributes: [:image])
end
And also,why you are using protected? i guess you should be using private.
I know there are alot of these kinds of posts on SO, and I think Ive read and tried each of them, all without success.
I have Post and Image models that I need to work together with a many to one relationship.
class Post < ActiveRecord::Base
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :post
mount_uploader :file, images_uploader
end
Here is the post_parms declaration in my posts controller, which includes all of the fields in my image model migration.
private
def post_params
params.require(:post).permit(:title, :content, image_attributes: [:id, :post_id, :file])
end
and here is my post creation form where, I hope to allow multiple image asset creation with each post.
<%= form_for #post, html: {class: "pure-form pure-form-stacked"} do |post| %>
<%= post.fields_for :image, :html => { :multipart => true } do |image| %>
<%= image.label :file, "Upload Image:" %>
<%= image.file_field :file, multiple: true %>
<% end %>
<fieldset class="post-form">
<%= post.label :title %>
<%= post.text_field :title %>
<%= post.label :content %>
<%= post.text_area :content, :class => "redactor", :rows => 40, :cols => 120 %>
</fieldset>
<div class = "button-box">
<%= post.submit class: "pure-button pure-button-primary" %>
<%= link_to "Cancel", posts_path, :class => "pure-button" %>
</div>
Despite repeated effort and reading every post I can find on this topic, I'm still getting:
Unpermitted parameters: image
The trouble here is that this error provides no clue where to start looking for the problem. Since Im not really sure where to look next I thought I would post it here looking for more professional opinions.
Update the Post model as below:
class Post < ActiveRecord::Base
has_many :images
accepts_nested_attributes_for :images ## Add this
end
This way upon form submission you would receive the image attributes in key images_attributes and not image which you are currently receiving which is causing the warning as Unpermitted parameters: image
As you have 1-M relationship between Post and Image
You need to update post_params as below:
def post_params
params.require(:post).permit(:title, :content, images_attributes: [:id, :post_id, :file])
end
Use images_attributes (Notice plural images) and NOT image_attributes (Notice singular image)
And change fields_for in your view as
<%= post.fields_for :images, :html => { :multipart => true } do |image| %>
Use images (Notice plural) and NOT image (Notice singular)
UPDATE
To resolve uninitialized constant Post::Image error
Update Image model as below:
class Image < ActiveRecord::Base
belongs_to :post
## Updated mount_uploader
mount_uploader :file, ImagesUploader, :mount_on => :file
end
Also, suggested to remove multiple: :true from
<%= ff.file_field :file, multiple: true %>
I am currently using paperclip to upload images of items to my site. I set up my paperclip exactly as https://github.com/thoughtbot/paperclip. I uploaded pictures to my site but then nothing is saved to the database. There's also images found in my public folder.
in my config,
Paperclip.options[:command_path] = "/opt/local/bin/"
In my item.rb
class Item < ActiveRecord::Base
attr_accessible :photo_file_name, :photo_content_type, :photo_file_size,
:photo_updated_at
has_attached_file :photo
end
class AddPhotoColumnToItem < ActiveRecord::Migration
def self.up
add_column :items, :photo_file_name, :string
add_column :items, :photo_content_type, :string
add_column :items, :photo_file_size, :integer
add_column :items, :photo_updated_at, :datetime
end
...
end
items/_form.html.erb:
<%= form_for #item, :html => { :multipart => true } do |f| %>
<%= f.error_messages %>
<p>
<%= f.file_field :photo %>
</p>
<p><%= f.submit %></p>
<% end %>
and finally items_controller.rb (I am using cancan)
class ItemsController < ApplicationController
load_and_authorize_resource
def edit
end
def update
if #item.update_attributes(params[:item])
redirect_to #item, :notice => "Successfully updated item."
else
render :action => 'edit'
end
end
end
I checked with firebug that an image is indeed uploaded. I even puts params and I got this:
Parameters: {"utf8"=>"✓", authenticity_token"=>"XB0ptrmoxqRIakUB4YCBmbpYm2Pjex8KNm9g0pscpgo=",
"item"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0x007f9c5460ef80 #original_filename="lindsay-lohan.jpg",
#content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"item[photo]\"; filename=\"lindsay-lohan-boobs.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/var/folders/14/gbn6ww_d1fs0lrcw22w50xdr0000gn/T/RackMultipart20110909-26576-auv9vl>>}, "commit"=>"Update Item", "id"=>"1"}
Anyone know why this is not working?
attr_accessible i think must be just attr_accessible :photo