Topic: I am Unable to Validate the file field "validates_presence_of :photo"
Hi...
I am Kranthi. I am working on Rails. Your Example is very good. But, for me the Validate code is not working.
validates_presence_of :location, :message => "Missing required field location"
acts_as_taggable
I am getting an error for "acts_as_taggable"
Please.... Help me....
MY CODE IS LIKE THIS:
================
MODEL:
======
class User < ActiveRecord::Base
validates_presence_of :firstname, :lastname, :username, :role, :message => ": Should not be null."
acts_as_taggable #this is reporting an Error for me
def upload(params)
path = get_path(params)
File.open(path, "wb") { |f| f.write(params[:photo].read) }
end
def get_path(params)
if params[:photo]
name = params[:photo].original_filename
directory = FileUtils.mkdir_p("public/users/"+username)
path = File.join(directory, name)
return path
else
return "error"
end
end
def get_url(params)
name = params[:photo].original_filename
directory = "data"
path = File.join(directory, name)
puts name
return name
end
end
CONTROLLER:
==========
class UsersController < ApplicationController
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.upload(params[:user])
@user.photo = @user.get_url(params[:user])
puts @user.photo
if @user.save
flash[:notice] = 'User was successfully created.'
format.html { redirect_to(@user) }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
end
end
VIEW:
=====
<h1>New user</h1>
<% form_for(@user, :html => {:multipart => "true"}) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :firstname %><br />
<%= f.text_field :firstname %>
</p>
<p>
<%= f.label :lastname %><br />
<%= f.text_field :lastname %>
</p>
<p>
<%= f.label :username %><br />
<%= f.text_field :username %>
</p>
<p>
<%= f.label :photo %><br />
<%= f.file_field :photo %>
</p>
<p>
<%= f.label :role %><br />
<%= f.text_field :role %>
</p>
<p>
<%= f.label :inuse %><br />
<%= f.check_box :inuse %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', users_path %>
MY PROBLEM:
==========
I am unable to perform validations for :photo field. Whether it is empty or not... I want to validate: vlidate_presence_of and validates_format_of and validate_filesize_of and all these things.....
Please Give me a Suggestion How to get validations.... for File Upload field :photo
And one more thing... I am using Google Chrome.. it is not providing me the full path of that file.