Search by ignoring data space in activecord

Asked 1 years ago, Updated 1 years ago, 71 views

http://tutty.info/521
How do I run these queries in Activeecord?

rails-activerecord

2022-09-30 20:16

2 Answers

This is what it looks like if you try to write only with ActiveRecord (and AREL), but I think it would be easier to understand if you write SQL directly.

Item.where(
  Arel::Nodes::NamedFunction.new(
    "REPLACE", [
      Arel::Nodes::NamedFunction.new(
        "REPLACE",
        [Item.arel_table [:name], "", "]
      ),
      " ", ""
    ]
  ) .matches ("Foo%")
)

SQL statements generated:

SELECT "items".* FROM "items"
WHERE REPLACE (REPLACE("items". "name", '', '', ') LIKE 'Foo%'

It may be a good idea to change the conditions dynamically (for example, by user input).


2022-09-30 20:16

Why don't you use where , or find_by_sql?

T.where ("REPLACE(key, '', '), '', ') LIKE?", "% Search String %")
T.find_by_sql("SELECT key, value FROM t WHERE REPLACE(REPLACE(key, '', '', ')LIKE?", % Search String %")")


2022-09-30 20:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.