I wrote a little ruby script, which connects itself to a mysql database and creates a table (if this table doesn't exist yet). After this the script should store content in this table I try to store this data using:
Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
I also tried
Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl")
but it seems to do the same because I always get the error:
Mysql::Error: Table 'my-username.my-dbname' doesn't exist: SHOW FULL FIELDS FROM table-name
SO this is what I got so far:
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "my-username",
:password => "my-password",
:database => "my-db-name",
:encoding => "UTF8"
)
table_name = "my_table"
unless ActiveRecord::Base.connection.tables.include? table_name
ActiveRecord::Schema.define do
create_table :"#{table_name}" do |table|
table.column :foo, :string
table.column :bar, :string
table.column :blallala, :string
end
end
end
class Table < ActiveRecord::Base
self.table_name = "#{table_name}"
end
Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
#Table.new(:foo => "bar", :foobar => "something", :blallala => "blololl")
So the question is: How do I actually create a columo/row and why does Table.create(:foo => "bar", :foobar => "something", :blallala => "blololl")
not work?
This worked for me:
# establish connection here
class Table < ActiveRecord::Base
self.table_name = "the_table"
end
unless Table.table_exists?
ActiveRecord::Schema.define do
create_table :the_table do |table|
table.column :foo, :string
table.column :bar, :string
table.column :blallala, :string
end
end
end
Table.create(:foo => "bar", :bar => "something", :blallala => "blololl")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.