【问题标题】:Can I create new ActiveRecord model with parent model & child model IN BULK?我可以用父模型和子模型批量创建新的 ActiveRecord 模型吗?
【发布时间】:2019-07-06 21:50:13
【问题描述】:

我想通过一种方法创建一些 ActiveRecord 模型。

我的记录如下。

class Company < ApplicationRecord
  has_many :users
  has_many :teams
  has_many :participations
end

class User < ApplicationRecord
  belongs_to :company
  has_many :participations
  has_many :teams, through: :participations
end

class Team < ApplicationRecord
  belongs_to :company
  has_many :participations
  has_many :users, through: :participations
end

class Participation < ApplicationRecord
  belongs_to :company
  belongs_to :user
  belongs_to :team
end

我的环境。

$ ruby -v
ruby 2.4.5p335 (2018-10-18 revision 65137) [x86_64-darwin17]
$ rails -v
Rails 5.0.7.1

我试过这个。但出现错误。

u = User.create(
  company: Company.create,
  teams: [
    Team.create(company: Company.create)
  ]
)
irb(main):021:0* u.errors
=> #<ActiveModel::Errors:0x00007faf7f5668b0 @base=#<User id: nil, company_id: 25, name: nil, created_at: nil, updated_at: nil>, @messages={:participations=>["is invalid"]}, @details={:participations=>[{:error=>:invalid}]}>
irb(main):022:0> u.participations
=> #<ActiveRecord::Associations::CollectionProxy [#<Participation id: nil, company_id: nil, user_id: nil, team_id: 15, created_at: nil, updated_at: nil>]>

我可以通过 ONE LINE 创建一些记录吗?还是不能??

【问题讨论】:

  • 您可以使用诸如bulk_insert 之类的gem。但它不会运行您的模型级验证(不过,您可以在批量插入之前手动运行它们)。据我所知,ActiveRecord 不支持批量导入。因此,您的选择是使用循环(如果您愿意,可以通过一些包装方法),或者在 SQL 中进行批量插入,跳过 ActiveRecord。
  • 感谢您的评论!我知道bulk_insert。但我不能用那个宝石解决我的问题。我的问题不是将模型作为多条记录导入,而是通过一种创建方法导入一些多个模型... :(
  • 如果您的问题是 ActiveRecord 是否支持这一点 - 那么恐怕答案是否定的。但是,如果您不介意在循环中创建记录,那么您可以创建一个实用方法来为您完成。

标签: ruby-on-rails ruby sqlite activerecord


【解决方案1】:

你不能在一行中做到这一点。您正在尝试实例化并传递仅需要 id 的整个 Company 对象。此外,由于尚未创建用户,因此无法将 user_id 附加到该公司。

您可以在一个方法中完成所有这些操作,但这可能是一个坏主意,原因有很多。我建议将您的逻辑分解为易于测试和维护的多种方法。

【讨论】:

  • 感谢您的评论 :) 我理解您认为一行是反模式的想法。我把这种方法打破了多线。 rb company = Company.create; teams = [Team.create(company: company)]; user = User.create( company: company, teams: teams ) 但我仍然遇到同样的错误...如何通过 ActiveRecord::Relation 创建参与记录??
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
相关资源
最近更新 更多