我有两个模型通过中间模型加入
class Integration < ActiveBase
has_many :integration_records
has_many :records, through: :intragration_records
end
class IntegrationRecords < ActiveBase
belongs_to :integrations
belongs_to :records
end
class Records < ActiveBase
has_many :integration_records
has_many :integrations, through: :intragration_records
end
现在,IntegrationRecords的JSON数据列默认为nil。
我想创建一个集成,带有相应的记录并将数据添加到integration_records上的数据列
我在考虑这样的事情,但没有成功:
Integration.create!(whatever_data).integration_records.create(data: {}).records.create(whatever)
这失败了......我注意到它会自动为
创建一条记录 Integration.create!(whatever_data).integration_records.create(data: {})
接下来的想法是:
Integration.create!(whatever_data).integration_records.create(data: {}).records.update(whatever)
没有工作。帮助他人!
答案 0 :(得分:0)
也许你可以一步一步地尝试。 1-创建集成 2-创建integration_record 3-创建记录
integration = Integration.create!(whatever_data)
integration_record = integration.integration_records.create!(data: {})
record = integration_record.records.create!(data: {})
您可以添加一项交易,以确保仅在integration
和integration_record
创建时才会记录record
。
答案 1 :(得分:0)
这实际上是&lt;&lt;运营商是为了。您当前的代码不起作用,因为您的integration_records返回一个空数组,并且您无法运行&#34;创建&#34;在一个空数组。 :)
所以有一个选择:
class Integration < ActiveBase
has_many :integration_records
has_many :records, through: :intragration_records
end
class IntegrationRecords < ActiveBase
belongs_to :integrations
belongs_to :records
end
class Records < ActiveBase
has_many :integration_records
has_many :integrations, through: :intragration_records
end
i = Integration.create!(data)
i.records << Record.create!(data)
应该这样做。