How to insert primary key value explicitly? - ruby-on-rails

I have a table called messages and here is the table structure, I don’t want id is auto increment field but it should be a primary key for that table.
Here is table structure for messages
CREATE TABLE `messages` (
`id` INT(11) NOT NULL,
`user_id` INT(11) NOT NULL,
`text` VARCHAR(255) NOT NULL,
`source` VARCHAR(100),
`created_at` DATETIME DEFAULT NULL,
`updated_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`)
);
while insert the data into table I am using below hash object
msg['id'] = 12345;
msg['user_id'] = 1;
msg['text'] = 'Hello world';
If I save this hash into messages table, id is not inserting
message = Message.new(msg);
message.save!
Rails is building insert sql with out id, so id value is not inserting messages table.
How insert the id value in table, This the insert sql rails build with out using id field
INSERT INTO `users` (`updated_at`, `user_id `, `text`, `created_at`) VALUES('2010-06-18 12:01:05', '1', 'Hello world', '2010-06-18 12:01:05');

Setting ID value is often useful when migrating from legacy data or - as I am doing right now - merging two apps while preserving FK integrity.
I just scratched my head for a while and it seems you have to set the PK value before calling save. After the record is saved, ActiveRecord ignores #id= or update_attribute . So while setting up the record from an attribute hash I use:
article = Article.new(attrs)
article.id = attrs["id"]
article.save!

You're working against the way rails works. ActiveRecord reserves the use of the id column and manages it for you.
Why should id not be an auto-incrementing column if it's the primary key?
Why do you need to control its value?
If you need an id column you can control yourself, add another one. It won't be the primary key, but you can make it a unique index too.

Related

utc_current as default value in informix

Use utc_current as default value in a field of an informix database table.
My idea is to do something like this, so that when that record is inserted or updated, the value is automatically increased since datetime or timestamp doesn't work for me.
CREATE TABLE tab1
(
id VARCHAR(128) NOT NULL,
update_ts integer DEFAULT dbinfo('utc_current') ,
modcount BIGINT,
);

Unable to find column names in a FK constraint

I have created two tables in Snowflake.
create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);
create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.
EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.
SHOW IMPORTED KEYS IN TABLE <fk_table_name>;
Updated answer:
I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:
show exported keys in account; -- Foreign keys
show primary keys in account;
When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:
show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";
You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.
maybe you can try to query this view: INFORMATION_SCHEMA.TABLE_CONSTRAINTS
Note: TABLE_CONSTRAINTS only displays objects for which the current role for the session has been granted access privileges.
For more see: https://docs.snowflake.net/manuals/sql-reference/info-schema/table_constraints.html

Creating a 'join' table - sqlite3

I think I'm pretty close on this one, but can't get it to click.
I've got two simple tables set up.
Table A:
CREATE TABLE customer(
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
create_time TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
I've got two rows of data populating correctly in Table A.
Table B:
CREATE TABLE address(
...> id INTEGER PRIMARY KEY,
...> street_address_1 TEXT NOT NULL,
...> street_address_2 TEXT,
...> street_address_3 TEXT,
...> city TEXT NOT NULL,
...> state TEXT NOT NULL,
...> zip TEXT NOT NULL);
And I've successfully imported a CSV file into that table.
I'm trying to create a 3rd table that joins Table A to Table B with the use of Foreign Keys.
I can create the table with the code below, but when I try to select the table, I'm getting a blank, which means I'm obviously doing something wrong. I'm expecting to see data where the two tables overlap on mutual Id numbers, i.e. where the ID from customer = Id from address I'd like to see the data from both tables for those rows appear in Table C.
Table C (the join table):
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL,
street_address_1 TEXT NOT NULL,
street_address_2 TEXT,
street_address_3 TEXT,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id)
);
Thanks!
I imported the data to the address table using this:
sqlite> .mode csv
sqlite> .import address.csv address
I manually typed in data to the first table using this:
insert into customer(first_name, last_name, email, password)
values('Ad','Mac','a.Mac#gmail.com','Mab'),('Brian','Obrien','bob#example.com','123456');
Don't duplicate the data in your join table (often called a bridge table). This should do for Table C:
CREATE TABLE customer_address(
id INTEGER PRIMARY KEY,
customer_id INTEGER,
address_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customer(id),
FOREIGN KEY (address_id) REFERENCES address(id));
Duplicating columns is bad practice because it 1)defeats the purpose of using a relational model; 2)can lead to conflicting records if information is updated or deleted in one table, but not another.
Furthermore, you shouldn't have street_address_1, street_address_2, street_address_3 all in the same table. That's a violation of First Normal Form. Think of it this way, can a person have more than three addresses? Can they have two addresses in different cities? Do all three of those addresses have the same zip?

Rails 3.1: Is there any way I can view which indexes have been created for my model?

I'm having a problem with my ActiveRecord exception handling and I suspect some of the indexes haven't been created as I thought they did. How can I view the indexes that have been created for my model?
Thanks so much in advance for your wisdom!
You can just look in your db/schema.rb where all the structure of the database is explicitly listed.
Assuming you are using MySQL, from your command line:
$ rails dbconsole
mysql> show create table users;
users | CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT '',
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `index_users_on_email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=latin1 |
Any "KEY" lines are your indexes.

Best DB grid to use with lots of lookup fields

I have a table with a couple foreign keys, something like this:
CREATE TABLE project.gl(
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
glaccount_id INT(11) UNSIGNED NOT NULL,
project_id INT(11) UNSIGNED NOT NULL,
booking_id INT(11) UNSIGNED NOT NULL,
cc_id INT(11) UNSIGNED DEFAULT NULL,
cu_id INT(11) UNSIGNED DEFAULT NULL,
PRIMARY KEY (id),
INDEX FK_gl_booking_id (booking_id),
INDEX FK_gl_cc_id (cc_id),
INDEX FK_gl_cu_id (cu_id),
INDEX FK_gl_glaccount_id (glaccount_id),
INDEX FK_gl_project_id (project_id),
CONSTRAINT FK_gl_booking_id FOREIGN KEY (booking_id)
REFERENCES project.booking (id) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT ......
I would like to display this in a DBGrid, but of course I don't want all the *_id's to show, but instead the data the id points to.
I don't want to use a query to resolve the id's, (for now) I want to use a plain TTable.
Which DBGrid variant would you recommend that can lookup foreign keys, using something like a DBLookupComboBox in the foreign key cell?
Just create a lookup field. Then the TDBGrid automatically shows a combobox for that column where you can select from the available values. The key field is automatically updated then.
See also TDBGridEh from Ehlib, it is more "light" than ExpressQuantumGrid but pretty powerful. It is a commercial product.
I do use the ExpressQuantumGrid from DeveloperExpress for this and many other tasks. It is very powerfull and mature and can have Lookup-Columns. But it is commercial and it is a very "heavy" component.

Resources