user211662
user211662

Reputation: 18427

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

Upvotes: 4

Views: 12323

Answers (6)

Viktor Ivliiev
Viktor Ivliiev

Reputation: 1324

My solution: :)

scope :full_name_contains, lambda { |query| 
  full_name = Arel::Nodes::NamedFunction.new('concat', [
      arel_table[:first_name], 
      Arel::Nodes.build_quoted(' '), 
      arel_table[:last_name]
    ]
  )

  where(full_name.matches("%#{query}%"))
}

def full_name
  "#{first_name} #{last_name}"
end

Upvotes: 0

Extending @Chase Gilliam response, this is the query for a MySQL DB

User.select("id, CONCAT(name, last_name) as value")

Hope that helps

Upvotes: 1

techdreams
techdreams

Reputation: 5585

Use # when joining two field with different datatypes.

For instance, adding one integer and string with + will give an error.

class User < ActiveRecord::Base
  def name
    "#{first_name} #{last_name}"
  end
end

Upvotes: 1

Chase
Chase

Reputation: 2826

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        |
+----+--------------------+

Upvotes: 8

bobbywilson0
bobbywilson0

Reputation: 1072

in your model:

def full_name
  [first_name, last_name].join(' ')
end

Upvotes: 10

Jordan Running
Jordan Running

Reputation: 106027

I think virtual attributes are right up your alley. This Railscast explains them, with an example that looks just like your use case.

Upvotes: 2

Related Questions