开发者

concat two fields activerecord

I'm so use开发者_高级运维d 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


in your model:

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


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


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


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


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

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

Hope that helps


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜