has_many通过中间模型不创建,但创建一个模型的副本

我有两个模型由中间模型连接

class Integration < ActiveRecord::Base has_many :integration_records has_many :records, through: :integration_records end class IntegrationRecord < ActiveRecord::Base belongs_to :integration belongs_to :record end class Record  (0.1ms) BEGIN SQL (8.7ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]] SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]] (0.4ms) COMMIT i.records => [one record] Record.all.count => 2 i.integration_records => # 

注意id nil

  IntegrationRecord.all => # IntegrationRecord.create => # 

注意id nil

  Record.create.integrations.create => (0.1ms) BEGIN SQL (8.7ms) INSERT INTO "integrations" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:02 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:02 UTC +00:00]] SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]] (0.4ms) COMMIT 

不知道为什么会发生这种情况,在i.records.create(whatever)输出的情况下:

  SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", Sat, 03 May 2014 00:31:06 UTC +00:00], ["updated_at", Sat, 03 May 2014 00:31:06 UTC +00:00]] (0.4ms) COMMIT INSERT INTO "integration_records" ("created_at", "data", "integration_id", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Sat, 03 May 2014 15:57:05 UTC +00:00], ["data", {}], ["integration_id", 5], ["updated_at", Sat, 03 May 2014 15:57:05 UTC +00:00]] 

我应该注意,由于某种原因,当我在rails 4.0.4中创建一个新应用程序时,我仍然遇到了这个问题。 但是,当我更改模型的名称,特别是Record模型时,它的工作原理非常好。 所以当我把它Recordrow根本没问题。

根据您当前的关联设置,您只需按照这些简单的说明一步一步完成

  1. 创建集成记录

     ## this will create an "integration" record in "integrations" table integration = Integration.create(whatever) 
  2. 创建关联的Record记录

     ## this will create an associated "record" entry in "records" table ## PLUS this will also created an associated record in "integration_records" table integration.records.create(whatever) 
  3. 查看关联的记录和关联的integration_records

     ## Display all the "records" entries associated to this particular integration integration.records ## Display all the "integration_records" entries associated to this particular integration integration.integration_records 

UPDATE

i.records.create(whatever)创建了2条记录,发现该问题与表的名称records有关。 一旦改变一切正常。 看起来像records是保留字。

此外,OP发现此链接表明记录是保留的