Seems the validation can’t work good!
I have 2 models: user and profile. a user is with a profile, there are
stored in different tables in database,(user is in
users(user_id,email,password,…),profile is
profiles(firstname,lastname,user_id,…). and all operations are
implement in UserController. I want to edit and update the profile, the
URL like “http://yourdomain/users/editprofile”, but seems the validation
of first name and last name doesn’t work. Why?
the code like below:
----------------code--------------------
class User < ActiveRecord::Base
has_one :profile
validates_presence_of :password,:on => :create
validates_format_of with =>
/\A([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})\Z/i
validates_uniqueness_of :email, :on => :create
end
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :firstname,:message=>“First name is required”
validates_presence_of :lastname,:message=>“Last name is required”
end
--------- code end-------
a user has a profile, and in the database, profiles table has a user_id.
there is no controller for Profile model, and all operations are
included in user_controller, the operations include singup, edit
profile, update profile.
UserController like below:
-----UserController Code–
class UsersController < ApplicationController
before_filter :login_required, :only => [:home, :editprofile,
:updateprofile, :changepass, :getloan, :createdealing, :history]
def index
end
def home
render :layout => ‘home’
end
def editprofile
unless current_user.profile.nil?
@profile = current_user.profile
end
…
end
def updateprofile
if current_user.profile.nil?
@profile = Profile.new(params[:profile])
@profile.user = current_user
begin
@profile.save!
rescue
…
end
else
@profile = current_user.profile
unless @profile.update_attributes(params[:profile])
end
.....
end
…
----code end—
The view for updating profile is like below:
------------/users/editprofile.rhtml----
<%= error_message_for ‘profile’%>
% form_for :profile,@profile,
:url => {:action => “updateprofile”,:i=>@params[“i”]},
:html => {:class => ‘required-validate’} do|form| %>
Your Personal Contact Information
------end---------
Here, first name and last name is required. In updateprofile
function,@profile.update_attributes(params[:profile]) will be failure,
if the first name or last name is empty. but why it doesn’t give any
errors in view page.<%= error_message_for ‘profile’%> doesn’t work!
please advice.
|