Reputation: 15274
I'm writing an insert with a select:
my_object_id = 7
id_list = [1,2,4,5]
TEST_TEMPLATE = %Q{
INSERT INTO tests
(test_id, data_id, text, created_at, updated_at)
select #{my_object_id}, data_id, text, created_at, updated_at
from tests where id in (#{id_list})
}
ActiveRecord::Base.connection.execute(TEST_TEMPLATE);
I get error that I cannot change the constant. How do I inject values into a string so I can use it in my insert/select statements?
How can this be solved in Ruby?
Upvotes: 0
Views: 178
Reputation: 14715
Here's a bit of an explanation to @SergioTulentsev answer:
You should change the first letter of TEST_TEMPLATE
to lowercase, because variables starting with uppercase letters are not actually variables, they are constants, so you shouldn't change them.
As @SergioTulentsev shows in his code, you should change every letter to lowercase to match the style-conventions used in Ruby.
Upvotes: 2
Reputation: 230336
There's no reason to make it a constant.
my_object_id = 7
id_list = [1,2,4,5]
test_template = %Q{
INSERT INTO tests
(test_id, data_id, text, created_at, updated_at)
select #{my_object_id}, data_id, text, created_at, updated_at
from tests where id in (#{id_list})
}
ActiveRecord::Base.connection.execute(test_template)
Upvotes: 1