为什么rails在insert语句中手动指定主键ID?

Mic*_*eal 5 ruby oracle ruby-on-rails ruby-on-rails-3 rails-activerecord

我使用rails has_many_belongs_to_many关联如下:

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
Run Code Online (Sandbox Code Playgroud)

我的联接表如下:

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
);
Run Code Online (Sandbox Code Playgroud)

当我尝试创建新记录时,如下所示:

role = MemberRole.create(name: role_params["name"], org_id: role_params["org_id"], permission_ids: role_params["permission_ids"])
Run Code Online (Sandbox Code Playgroud)

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

插入"MEMBER_ROLES_PERMISSIONS"("MEMBER_ROLE_ID","PERMISSION_ID")值(66,8)

上述方法的问题是我的member_roles表具有如下创建的序列和触发器:

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;
Run Code Online (Sandbox Code Playgroud)

由于上面的内容,插入表内的"ID"是67而不是66.

rails是否应该尝试手动插入id?有没有办法告诉rails不处理id插入并让oracle触发器处理它?

Ash*_*arS 1

这是因为 oracle 增强适配器的工作方式。检查这些代码行,它用于从序列中获取值,因此我假设 Active record 将专门使用 create 语句发送此值,因此 ID 将显示在查询日志中。