Ruby on rails 一次插入所有子记录
我有这些模型:Ruby on rails 一次插入所有子记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有这些模型: class Project < ActiveRecord::Base has_many :task_links, -> { includes(:task).order("tasks.name") }, dependent: :destroy has_many :tasks, through: :task_links class TaskLink < ActiveRecord::Base belongs_to :project belongs_t
class Project < ActiveRecord::Base
has_many :task_links, -> { includes(:task).order("tasks.name") }, dependent: :destroy
has_many :tasks, through: :task_links
class TaskLink < ActiveRecord::Base
belongs_to :project
belongs_to :task
class Task < ActiveRecord::Base
has_many :task_links, dependent: :destroy
has_many :projects, through: :task_links
class项目{includes(:task).order(“tasks.name”)},依赖::destroy
有很多:任务,通过::任务链接
类TaskLink
我想创建一个after_create回调,它将自动为所有活动项目和新创建的任务创建所有任务链接。我可以通过在活动项目上循环并为每个项目创建一个task_链接来做到这一点,但我想知道是否有更好的方法来做到这一点?最好使用一个大的insert命令而不是xxx。我不确定为什么需要在创建后使用
,因为我认为在创建之前使用会很好。使用创建前的,您可以在保存新的任务时保存所有任务链接
class Task < ActiveRecord::Base
has_many :task_links, dependent: :destroy
has_many :projects, through: :task_links
before_create :create_task_links
def create_task_links
# I'm assuming that the where below satisfies "all active projects"
Project.where(active: true).find_each do |proj|
# build only creates objects but does not save them to your database
self.task_links.build(project: proj)
end
end
end
类任务