Ruby: How to Dynamically Replace Parameters in Native Pg Gem

Is there a more concise way to check if PGResult is empty?

ntuples, a typo? It is faster and concise to use zero? than == 0

if res.num_tuples.zero?

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

Rails Routing, how to put username before posts url?

In routes.rb

1 =>

get '/:username/posts/:id', to: "controller#action", as: my_custom_route

Here by you need to pass 2 dynamic param value with this path 1 -> username, 2-> post_title

my_custom_route_path(username: username_value, id: post_title)

2 =>

If you want just username as static in every routes for this action then

get '/username/posts/:id', to: "controller#action", as: :my_custom_route

Here you need to pass only one dynamic param that is post_title

my_custom_route(id: post_title)


Related Topics



Leave a reply



Submit