Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concat two fields activerecord

I'm so used to oracle where you can simply

concat(field1, ' ', field2)

but if I'm using activerecord to find the field1 and field2, and I need a space in between, how do I accomplish this?

Cheers for all your help

like image 747
user211662 Avatar asked Dec 01 '22 11:12

user211662


2 Answers

in your model:

def full_name
  [first_name, last_name].join(' ')
end
like image 58
bobbywilson0 Avatar answered Dec 05 '22 03:12

bobbywilson0


For posterity and future googlers, you can do the following assuming postgres(maybe mysql?):

User.select("(first_name || ' ' || last_name) as name").where(organization: current_user.organization)

The select uses the || SQL operator to concat the strings from the fields first_name and last_name, and as name returns the result in a column "name".

Which might return:

+----+--------------------+
| id | name               |
+----+--------------------+
| 3  | Ada Lovelace       |
| 18 | Alan Turing        |
+----+--------------------+
like image 26
Chase Avatar answered Dec 05 '22 02:12

Chase