Rails adding extra field on signup in devise - ruby-on-rails

I am using devise for my authentication .On sign up page devise is giving 3 fields and I am trying to add an extra field file_field ..But it is giving me error.I am using carrier wave for file uploading .Also I have a attachment column in my users table but the file is not inserting. I am getting error on console. Unpermitted parameters: attachment.Here is my code can anyone help me in resolving this
[console]
Started POST "/users" for 127.0.0.1 at 2016-02-12 12:15:32 +0530
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"M6F9ME0zJkAxyHPETI8qmCf4a8u8bn4wTmZI0v5xtPQ=", "user"=>{"email"=>"aniketshivam#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "attachment"=>#<ActionDispatch::Http::UploadedFile:0x000000040ed928 #tempfile=#<Tempfile:/tmp/RackMultipart20160212-13081-16e7tyg>, #original_filename="73273_773684942011_4_40639956_2125564_n.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"user[attachment]\"; filename=\"73273_773684942011_4_40639956_2125564_n.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Sign up"}
Unpermitted parameters: attachment
(0.1ms) BEGIN
User Exists (0.6ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'aniketshivam#gmail.com' LIMIT 1
SQL (0.3ms) INSERT INTO `users` (`created_at`, `email`, `encrypted_password`, `updated_at`) VALUES ('2016-02-12 06:45:32', 'aniketshivam#gmail.com', '$2a$10$kFDcpyXr1l9Mv7epJY3UMOrq9zyOInuQFQMVcqz34nHxvB.rNGk0C', '2016-02-12 06:45:32')
(34.2ms) COMMIT
(0.1ms) BEGIN
SQL (0.3ms) UPDATE `users` SET `current_sign_in_at` = '2016-02-12 06:45:32', `current_sign_in_ip` = '127.0.0.1', `last_sign_in_at` = '2016-02-12 06:45:32', `last_sign_in_ip` = '127.0.0.1', `sign_in_count` = 1, `updated_at` = '2016-02-12 06:45:32' WHERE `users`.`id` = 6
(40.8ms) COMMIT
Redirected to http://localhost:3000/posts
Completed 302 Found in 183ms (ActiveRecord: 76.3ms)
Started GET "/posts" for 127.0.0.1 at 2016-02-12 12:15:32 +0530
Processing by PostsController#index as HTML
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1
User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 LIMIT 1
Post Load (0.7ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` = 6 ORDER BY created_at DESC LIMIT 5 OFFSET 0
Rendered posts/index.html.erb within layouts/application (2.9ms)
<br>
[registration_controller]
class Users::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up).permit(:attachment)
end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.for(:account_update) << :attribute
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
[user.rb]
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :comments
mount_uploader :attachment, AttachmentUploader
def self.find_role(id)
User.find(id).roles
end
end
[registrations/new.html.erb]
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name,html: { multipart: true } ,url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %></div>
<div><%= f.label :password %> <% if #validatable %><i>(<%= #minimum_password_length %> characters minimum)</i><% end %><br />
<%= f.password_field :password, autocomplete: "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %></div>
<br/>
<div >
<%= f.file_field :attachment %>
</div>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
[attachment_uploader.rb]
# encoding: utf-8
class AttachmentUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploadsss/post/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :resize_to_fit => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end

Try following in registration_controller
before_filter :configure_sign_up_params
def configure_sign_up_params
devise_parameter_sanitizer.for(:sign_up).push(:attachment)
end

Related

undefined method `url' for "#<ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":String

I am using Carrierwave to upload picture, after uploaded, I got the error when go to show page:
undefined method `url' for "#ActionDispatch::Http::UploadedFile:0x007f8b6134d610>":String
<%= image_tag #product.picture.url if #product.picture? %>
Here is my code:
_form.html.erb
<div class="picture">
<%= f.file_field :picture %>
</div>
product.rb
class Product < ApplicationRecord
has_many :reviews, dependent: :destroy
mount_uploader :picture, PictureUploader
end
show.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #product.name %>
</p>
<strong>Picture:</strong>
<%= image_tag #product.picture.url if #product.picture? %>
</p>
<%= link_to 'Edit', edit_product_path(#product) %> |
<%= link_to 'Back', products_path %>
Anyone know how to solve the problem?
Update:
picture_uploader.rb
# encoding: utf-8
class PictureUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :resize_to_fit => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
Here is the version in Gemfile:
gem 'carrierwave', '0.11.2'
gem 'mini_magick', '4.5.1'
gem 'fog', '1.38.0'
I would check first strong params and add :picture attribute if it hasn't been added.
Then I would try to add this in your show views:
show.html.erb
<%= image_tag(#product.picture_url.to_s) %>
instead of this line of code:
<%= image_tag #product.picture.url if #product.picture? %>
In case that you have permissions problem, you can create config file:
config/initializers/carrierwave.rb
and add permissions:
CarrierWave.configure do |config|
config.permissions = 0666
config.directory_permissions = 0777
config.storage = :file
end
in model, you need add
Blockquote
mount_uploader :picture, PictureUploader
Blockquote

Undefined method `<<` in image upload

def create
#product = Product.find(1)
#product.images << params[:image]
#product.save
end
The schema is
t.string "images", default: [], array: true
I want the assign the image coming in params to the images array, if the image is already there. The new image should append, otherwise it should be the first one
Here is the Product model
class Product < ActiveRecord::Base
mount_uploader :images, ProductUploader
validates :name, presence: true
validates :price, presence: true
validates :availability, presence: true
validates :about, presence: true
validates :ref, presence: true
validates :texture, presence: true
validates :shipping, presence: true
validates :category, presence: true
validates :notes, presence: true
end
I generated the ProductUploader through carrierwave uploader command
class ProductUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process scale: [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process resize_to_fit: [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_whitelist
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
After uploading the image, the image shows up in params. But does not get saved in the table. Here is the screenshot of byebug
Edit:
I have made some progress
I updated the string [] to json for images like this
And instead of files coming like string, it's coming as file. Now the only problem is, I am unable to access the name properly name=\"image[avatar_1]\" in the params
"utf8"=>"✓", "authenticity_token"=>"JbtcVdUvPJIzSHycX0wdr349zcATDN51vSewI33nvHIKQdhxxgxWUEJz9ZsubNrgvq2ftO+DosHXWM8Tipce7w==", "image"=>{"avatar_1"=>#<ActionDispatch::Http::UploadedFile:0x007f2ba8377f78 #tempfile=#<Tempfile:/tmp/RackMultipart20160704-20497-1czlw3s.png>, #original_filename="no-save.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"image[avatar_1]\"; filename=\"no-save.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"submit", "controller"=>"upload", "action"=>"create"}
Here is the view file
<%= simple_form_for :image, method: :post, url: save_image_path do |f| %>
<%= f.file_field :avatar_1 %>
<%= f.submit :submit %>
<% end %>
here it is avatar_1. I need to change it in create code, but I am not accessing params itself properly
Let's divide your question into subproblems:
Database & controller
Your database and controller are working properly. No need to change anything!
Uploaded image
You uploaded image (in params[:image]) is a String, instead of a ActionDispatch::Http::UploadedFile. You should probably add the multipart form data to your form.
Change filename
You can access the uploaded filename with params[:image].original_filename. If you want to change the filename, then you can redefine the filename method for your CarrierWave handler (the last one, which is commented).

Devise: custom fields not saved after signing up Rails 4

I have installed devise gem in my app for registration. I have same issue like this question
I have generated Doctor model by
rails generate devise Doctor
And here is doctor.rb
class Doctor < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
I also generated controller by rails generate devise:controllers doctors
class Doctors::RegistrationsController < Devise::RegistrationsController
before_filter :sign_up_params, only: [:create]
before_filter :account_update_params, only: [:update]
#
# # GET /resource/sign_up
# def new
# super
# end
##
## # POST /resource
# def create
# super
# end
##
## # GET /resource/edit
# def edit
# super
# end
##
## # PUT /resource
# def update
# super
# end
##
## # DELETE /resource
# def destroy
# super
# end
protected
def sign_up_params
params.require(:doctor).permit(:first_name, :last_name, :email, :password, :password_confirmation, :gender, :contact_no, :about_me, :certification, :exp_summary, :username)
end
#
def account_update_params
params.require(:doctor).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password , :gender, :contact_no, :about_me, :certification, :exp_summary, :username)
end
# protected
# You can put the params you want to permit in the empty array.
#def configure_sign_up_params
# devise_parameter_sanitizer.for(:sign_up) << :first_name, :last_name, :gender, :contact_no, :about_me, :certification, :exp_summary, :username
#end
# You can put the params you want to permit in the empty array.
#def configure_account_update_params
# devise_parameter_sanitizer.for(:account_update) << :first_name, :last_name, :gender, :contact_no, :about_me, :certification, :exp_summary, :username
#end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
I have written in routes.rb file devise_for :doctor, :controllers => { sessions: "doctors/sessions"}.
Here is my logs from terminal after submitting Sign_up form
Started POST "/doctor" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8Dd5u5Qq+kLyAI+RaEuoSyjsxteHw4VBndQC+W5yjy0=", "doctor"=>{"username"=>"Test5", "first_name"=>"John", "last_name"=>"Smith", "contact_no"=>"8787878787", "gender"=>"true", "email"=>"john#smith.com", "about_me"=>"Test", "certification"=>"Test", "exp_summary"=>"Test", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameters: username, first_name, last_name, contact_no, gender, about_me, certification, exp_summary
(0.2ms) BEGIN
Doctor Exists (0.3ms) SELECT 1 AS one FROM `doctors` WHERE `doctors`.`email` = BINARY 'john#smith.com' LIMIT 1
SQL (0.2ms) INSERT INTO `doctors` (`created_at`, `email`, `encrypted_password`, `updated_at`) VALUES ('2014-12-04 11:22:20', 'john#smith.com', '$2a$10$as.WAOu05ET7RUtnsdTC2ucqotK5Ls2Z6iKWI.wW3gSuIwohYfoTW', '2014-12-04 11:22:20')
(116.8ms) COMMIT
(0.1ms) BEGIN
SQL (0.3ms) UPDATE `doctors` SET `current_sign_in_at` = '2014-12-04 11:22:20', `current_sign_in_ip` = '127.0.0.1', `last_sign_in_at` = '2014-12-04 11:22:20', `last_sign_in_ip` = '127.0.0.1', `sign_in_count` = 1, `updated_at` = '2014-12-04 11:22:20' WHERE `doctors`.`id` = 7
(56.6ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 254ms (ActiveRecord: 174.5ms)
Started GET "/" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Processing by HomeController#index as HTML
Doctor Load (0.3ms) SELECT `doctors`.* FROM `doctors` WHERE `doctors`.`id` = 7 ORDER BY `doctors`.`id` ASC LIMIT 1
Rendered home/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 32ms (Views: 30.5ms | ActiveRecord: 0.3ms)
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/home.css?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/turbolinks.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/home.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Why my custom fields are not saved? Where I do mistake?
Update
Controller Structure:
controllers
-> doctors
-> confirmations_controller.rb
-> omniauth_callbacks_controller.rb
-> passwords_controller.rb
-> registrations_controller.rb
-> sessions_controller.rb
-> unlocks_controller.rb
-> application_controller.rb
-> home_controller.rb
EDITED:
Okay! You were trying to override the devise controllers which is not required in your case. Follow these simple steps:
rails g model Doctor
Create your fields except email and password. Devise will take care of that.
rails g devise:install
rails g devise Doctor
In your ApplicationController:
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :address, :phone, :email) }
end
Please try to do like following. Hopes it work for you. :)
class RegistrationsController < Devise::RegistrationsController
def create
devise_parameter_sanitizer.for(:sign_up) << [:first_name, :last_name]
super
end
end

Rails 4 undefined method `import' for #<Class:0xa874498> when importing csv file

I'm following this railcast on how to import a csv file.
My csv file is called stg_pound.csv and has the following contents:
"FOREX RATES FOR DATES BETWEEN 2003-5-1 AND 2014-5-28, STG POUND",,,,
Date,Currency,Buy,Sell,Mean
01/01/03,STG POUND,147.5117,147.7939,147.653
01/02/03,STG POUND,147.837,148.1767,148.007
01/03/03,STG POUND,147.8006,148.1422,147.971
01/04/03,STG POUND,148.0311,148.3722,148.202
my app is setup as follows:
my forex index.html.erb :
<%= form_tag import_forexes_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
forexes_controller.rb
def import
Forex.import(params[:file])
redirect_to root_url, notice: "Imported"
end
forex.rb
# == Schema Information
#
# Table name: forexes
#
# id :integer not null, primary key
# published_at :datetime
# currency :string(255)
# buy :float
# sell :float
# mean :float
# created_at :datetime
# updated_at :datetime
#
def import
CSV.foreach(file.path, headers: true) do |row|
Forex.create! row.to_hash
end
end
routes.rb
resources :forexes do
collection { post :import}
end
application.rb
require 'csv'
When I try importing the stg_pound.csv file I get the following error:
undefined method `import' for #<Class:0xab2c6cc>
The following line from the forex_controller.rb file is highlighted:
Forex.import(params[:file])
However I can see the file has been picked since on the error page I'm seeing the following:
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"mGm6jN7uvoRVjVbSDE/vpprIQnpjiL60s4rETHT9mPA=",
"file"=>#<ActionDispatch::Http::UploadedFile:0xaa974dc #tempfile=#<Tempfile:/tmp/RackMultipart20140530-4261-z8fb9x>,
#original_filename="stg_pound.csv",
#content_type="text/csv",
#headers="Content-Disposition: form-data; name=\"file\"; filename=\"stg_pound.csv\"\r\nContent-Type: text/csv\r\n">,
"commit"=>"Import"}
At first I thought it was because :file had not been included in the strong_parameters so I went ahead and included the following in forex_controller strong parameters but it doesn't work
def forex_params
params.require(:forex).permit(:published_at, :currency, :buy, :sell, :mean, :file)
end
Firstly, your import method is an instance one, it needs to be class.
def self.import
# content
end
Secondly, you are passing parameters to it from the controller Forex.import(params[:file]) but not catching them.
def self.import(file)
# content
end

Why is my image attribute showing up as nil in post request?

Here's what shows in the server window when submitting the form:
Started POST "/seniors" for 127.0.0.1 at 2013-08-21 17:27:34 -0400
Processing by SeniorsController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"zWeveRhstI178IawtOka6TV2wdKwnpKq2J74VYYNf1U=", "senior"=>{"first_name"=>"Jane", "last_name"=>"dOE", "employer _id"=>"1"}, "commit"=>"Create Senior"}
(0.0ms) begin transaction
SQL (3.0ms) INSERT INTO "seniors" ("created_at", "employer_id", "first_name", "image", "last_name", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Wed, 21 Aug 2013 21:27:34 UTC +00:00], ["employer_id", 1], ["first_name", "Jane"], ["image", nil], ["last_name", "dOE"], ["updated_at", Wed , 21 Aug 2013 21:27:34 UTC +00:00]]
(107.7ms) commit transaction
Redirected to http://localhost:3000/seniors
Completed 302 Found in 120ms (ActiveRecord: 110.7ms)
The form:
<%=content_for :page do%>
<div class="menuTitle"><h1><%if #senior.new_record?%>New<%else%>Edit<%end%> Senior</h1></div>
<%=form_for #senior, :html=>{:multipart => true} do |f|%>
<div class="login form">
#<p>First Name: <%=f.text_field :first_name%></p>
<p>Last Name: <%=f.text_field :last_name%></p>
<p>Facility: <%=f.collection_select :employer_id, #employers, :id, :name%></p>
<p>Image: <%=f.file_field :image%></p>
<p><%=f.submit :class => "button red"%></p>
</div>
<%end%>
<%end%>
and model:
class Senior < ActiveRecord::Base
mount_uploader :image, ImageUploader
#attr_accessible :image
#attr_accessible :first_name, :last_name, :street1, :street2, :city, :state, :zipcode, :country, :phone, :image, :employer_id, :phin
attr_protected :nil
has_many :senior_users
has_many :short_forms
has_one :long_form
has_many :users, :as => :workers, :through => :senior_users
belongs_to :employer
def long_name
"#{self.last_name}, #{self.first_name}"
end
end
and image_uploader.rb:
# encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
#include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :scale => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
Problem solved thanks to the answer here: Rails file_field does not upload anything
The site I was brought on board to work on uses jQuery mobile which by default submits all forms using ajax, however files cannot be submitted via ajax. The solution was to add
:html => { :'data-ajax' => false }
to the form.
Im leaving this answer if anyone comes here again. Although it's true rails form_for POST via ajax does not support sending files via AJAX even with multipart: true, it can be done with the gem "remotipart". This way, there's no need to fallback to submit the form with full page refresh. In response to #xxyyxx answer.

Resources