【发布时间】: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