将记录与所有ID相关联

时间:2019-07-19 10:17:54

标签: ruby-on-rails ruby database

我有一个模型BenefitDesignation

在我的seeds.rb文件中,我想做类似的事情:

benefits = ['Health Insurance', 'Provident Fund']
benefits.each do |benefits|
  Benefit.create(name: benefits, designation_id: Designation.all.ids)
end

以便为已经存在的所有Designations添加福利'Health Insurance'和'Provident Fund'。 但是 Designation.all.ids 不起作用,该怎么做?

benefits的架构:

  create_table "benefits", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "designation_id"
    t.index ["designation_id"], name: "index_benefits_on_designation_id"
  end

3 个答案:

答案 0 :(得分:2)

如果我很了解您想要的是什么:

  • 指定可以带来很多好处
  • 福利可以有很多指定

您无法使用当前的数据库架构来实现。

您需要引入中间模型,如下所示:

create_table :benefits do |t|
  t.string :name
  t.timestamps null: false
end

create_table :designations do |t|
  t.string :name
  t.timestamps null: false
end

create_table :designation_benefits do |t|
  t.belongs_to :benefit, index: true
  t.belongs_to :designation, index: true
  t.timestamps null: false
end

然后

class Benefit < ActiveRecord::Base
  has_many :designation_benefits
  has_many :designations, through: :designation_benefits
end

class Designation < ActiveRecord::Base
  has_many :designation_benefits
  has_many :benefits, through: :designation_benefits
end

class DesignationBenefit < ActiveRecord::Base
  belong_to :benefit
  belong_to :designation
end

最后,您可以创建如下记录:

['Health Insurance', 'Provident Fund'].each do |name|
  benefit = Benefit.create!(name: name)
  benefit.designations << Designation.all
end

Designation.first.benefits.count # => 2

在此处查看示例和文档:

https://guides.rubyonrails.org/v4.2/association_basics.html#the-has-many-through-association

答案 1 :(得分:0)

使用福利表的当前结构您不能。

您可以做什么

解决方案1:

designation_id列数据类型更改为stringtext

然后将值另存为

  Benefit.create(name: benefits, designation_id: Designation.all.ids.join(','))

解决方案2:

BenefitDesignation模型之间建立更好的关联。

答案 2 :(得分:-1)

此解决方案对我有效,就像我想要的那样:

benefits = ['Health Insurance', 'Provident Fund']
designation_ids = Designation.all.pluck(:id)
benefits.each do |benefits|
    designation_ids.each do |designation|
        Benefit.create(name: benefits, designation_id: designation)
    end
end

designation_ids包含所有ID的列表,并且嵌套循环将benefits都添加到列表中的所有ID。