I’ve been toying over these two problems, but I’m hoping that someone
here might be able to provide a better idea.
-
Every user has their own id (current_user.id) and can add people to a
list with firstname and lastname fields. I understand that
validates_uniqueness_of with :scope should be able to compare at least
one of the fields, but can this validation be done against the combined
first and last name together?
-
Does anyone have a better reference for structuring conditions within
finds? Specifically, I’m trying to figure out how to adjust this query
to find matches between either lastname AND email or lastname and phone
(@contact.phone)
User.find(:first, :conditions => [“lastname = ? AND email = ?”,
@contact.lastname, @contact.email])
If anyone could lend a hand, I’d really appreciate it. Sorry if these
questions are a bit basic, as well.
For #2, something like this should work:
class User
def self.find_by_lastname_etc(lastname, firstname = nil, email = nil)
where_string = “lastname = :lname”
if !firstname.nil?
where_string += " AND firstname = :fname"
end
if !email.nil?
where_string += " AND email = :em"
end
self.find(where_string, {:lname => lastname, :fname => firstname,
:em => email})
end
end
Cheers,
-Roy
On Wed, Jul 23, 2008 at 1:17 PM, Rob Scott
[email protected] wrote:
I’ve been toying over these two problems, but I’m hoping that someone
here might be able to provide a better idea.
- Every user has their own id (current_user.id) and can add people to a
list with firstname and lastname fields. I understand that
validates_uniqueness_of with :scope should be able to compare at least
one of the fields, but can this validation be done against the combined
first and last name together?
Not using validates_uniqueness_of. You can however write your own
validation function using validates_each. See:
http://api.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html#M001045
- Does anyone have a better reference for structuring conditions within
finds? Specifically, I’m trying to figure out how to adjust this query
to find matches between either lastname AND email or lastname and phone
(@contact.phone)
User.find(:first, :conditions => [“lastname = ? AND email = ?”,
@contact.lastname, @contact.email])
You can just use a standard sql where fragment:
User.find(:first, :conditions => [“(lastname = ? AND email = ?) OR
(lastname = ? and phone = ?)”, @contact.lastname, @contact.email,
@contact.lastname, @contact.phone])