http://tutty.info/521
How do I run these queries in Activeecord?
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).
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 %")")
© 2025 OneMinuteCode. All rights reserved.