Newbie question.
I am trying to use ActiveRecord::Base.connection.execute(..) in a ruby 3.1 app and docs I have read seem to be straight forward but for the life in me I can seem to understand why I cant get the code below to work. The error message I am getting suggests that the execute function is looking for a column with the name of one of the values I am trying to save but I dont understand why.
Firstly, my db table structure is as follows:
create_table "countries", :force => true do |t|
t.string "iso3"
t.string "iso2"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
And the code Im playing with is as follows:
code = 'ZA'
name = 'South Africa'
ActiveRecord::Base.connection.execute("INSERT INTO countries ('iso3', 'iso2', 'name')
VALUES ('Null', #{code}, #{name})")
The error message I am getting is as follows:
SQLite3::SQLException: no such column: ZA: INSERT INTO countries ('iso3', 'iso2', 'name')
VALUES ('Null', ZA, SouthAfrica)
Where did you get the basis for this? Code of this variety is a sterling example of what not to do.
If you have ActiveRecord, then you have ActiveRecord::Model, and with that you’re on the right track and pretty much done. You don’t need to write raw SQL for routine things of this variety. It’s not necessary, and more, it’s extremely dangerous for the reasons you’ve just discovered. You can’t just shove random things in to your query or you will end up with nothing but trouble.
What you should be doing is declaring a model and then using it:
To insert once you have a model is made seriously easy:
A good ActiveRecord reference is invaluable as this facility will make your life significantly easier if you make use of it.
Within Rails you usually go about generating these automatically so that you have something rough to start with:
This will take care of creating the migration file, the model file, and some unit test stubs you can fill in later.