A really newbie question

Hi,

I have been playing around with Ruby after reading so much about it, and
so I started tweaking with auto generated scaffold.

But it seems like I must be missing something, can someone else please
help me take a look and give me a couple pointers? In short I was trying
to make a class User that has a method addupdate with 2 parameters
(alias and email) which would either update the existing record if a
match on either alias or email is found, or create a new record if no
matches are found.

But despite many tries it just doesn’t work. Did I set the accessor
parameters correctly?

Thanks.


class User < ActiveRecord::Base
attr_writer :alias, :email

def self.newuser?(p_alias, p_email)
user = find_first([“alias = ? OR email = ?”, p_alias, p_email])
if user.nil?
return true
else
return false
end
end

def self.addupdate(p_alias, p_email)
t_user = find_first([“alias = ? OR email = ?”, p_alias, p_email])
if t_user.nil?
t_user = User.new(:alias => p_alias, :email => p_email, :name =>
“”, :password => “”)
else
t_user.alias = p_alias
t_user.email = p_email
end
t_user.save
return t_user
end

protected
validates_presence_of :alias, :email
validates_uniqueness_of :alias, :on => :save
validates_uniqueness_of :email, :on => :save
validates_format_of :email, :with =>
/^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i, :on => :save
end

You’ll need to be more specific as to what doesn’t work with this
code. However, offhand I can see a few things…

First, what is the ‘attr_writer’ code for? If alias and email are
columns in your table, AR will automatically generate accessors and
mutators for your column names, so there may be problems with ruby
overriding the column mutator methods with its ‘attr_writer’.

Also, why have you put the validates stuff in under protected? Though
I don’t think it makes any difference to the actual functionality of
the code, putting them in there is meaningless as what you’re actually
doing with ‘validates_presence_of’ et al is calling methods on the
Class object of User at parse time to dynamically add the validations
to the model.

Also, bear in mind that your ‘t_user.save’ line will fail silently if
a validation rule fails - you should either check the return value of
save to ensure the record was saved properly or call ‘t_user.save!’ if
you want it to raise an exception for a problem.

Also, for the sake of brevity, this:

def self.newuser?(p_alias, p_email)
user = find_first([“alias = ? OR email = ?”, p_alias, p_email])
if user.nil?
return true
else
return false
end
end

could be replace with this:

Return true if the passed alias and email don’t exist in the ‘users’

table,

false otherwise

def self.newuser?(p_alias, p_email)
find_first([“alias = ? OR email = ?”, p_alias, p_email]).nil?
end

Hope that helps!

-DF