Why do rails manually define a primary key in an insert statement?

I use the rails has_many_belongs_to_many association as follows:

class MemberRole < ActiveRecord::Base attr_accessible :org_id, :name, :permission_ids has_and_belongs_to_many :permissions end class Permission < ActiveRecord::Base has_and_belongs_to_many :member_roles end 

My connection table is as follows:

 CREATE TABLE MEMBER_ROLES_PERMISSIONS ( member_role_id NUMBER(38,0) NOT NULL REFERENCES member_roles, permission_id NUMBER(38,0) NOT NULL REFERENCES permissions ); 

When I try to create a new record as follows:

 role = MemberRole.create(name: role_params["name"], org_id: role_params["org_id"], permission_ids: role_params["permission_ids"]) 

INSERT IN "MEMBER_ROLES" ("ID", "NAME", "ORG_ID") VALUES (: a1 ,: a2 ,: a3) [["id", 66], ["name", "test100"], [" org_id "," 2 "]]

INSERT IN "MEMBER_ROLES_PERMISSIONS" ("MEMBER_ROLE_ID", "PERMISSION_ID") VALUES (66, 8)

The problem with the above approach is that my member_roles table has a sequence and trigger created as follows:

 CREATE SEQUENCE MEMBER_ROLES_SEQ; set define off; CREATE OR REPLACE TRIGGER member_roles_bir BEFORE INSERT ON MEMBER_ROLES FOR EACH ROW BEGIN SELECT MEMBER_ROLES_SEQ.NEXTVAL INTO :new.id FROM dual; END; 

Due to the above, the "ID" inserted in the table is 67 instead of 66.

Should the rails even try to insert the identifier manually? Is there a way that I can say that the rails do not handle the id insertion and let the oracle trigger handle it?

+5
source share
1 answer

This is due to how the improved oracle adapter works. Check these lines of code. This is used to extract the value from the sequence, so I assume that the active record will be specifically sent using the create statement, and therefore the identifier appears in the query log.

+1
source

Source: https://habr.com/ru/post/1215235/


All Articles