简体   繁体   English

大规模创造和危害性关联

[英]Mass creation and association of habtm

I have 3 models (Genre, Mood, Tempo) each with a has_and_belongs_to_many association with another model (Track). 我有3个模型(流派,情绪,节奏),每个模型都具有与另一个模型(跟踪)的has_and_belongs_to_many关联。 The user can upload an Excel file with info for each track and I want to be able to create the respective records and add the association all at once in my update method. 用户可以上载带有每个轨道信息的Excel文件,而我希望能够创建各自的记录并在我的更新方法中一次添加所有关联。

I'm reading each row from the spreadsheet and creating arrays holding the genres, moods, and tempos that are to be associated with each track, but I'm not sure how to correctly create the association. 我正在从电子表格中读取每一行,并创建包含将与每个音轨相关联的流派,情绪和节奏的数组,但是我不确定如何正确创建该关联。

Something like: 就像是:

1.upto @worksheet.last_row_index do |index|
  row = @worksheet.row(index)
  genres = row[6].split(", ")
  genres.each do |g|
    Genre.find_or_create_by_name(g) // not sure what to do here exactly
  end
end

The Track ID is row[0]. 轨道ID为第[0]行。

I need to create each Genre if it doesn't exist, and associate that track with each. 如果每个流派不存在,我需要创建它们,并将该音轨与每个流派关联。 If the genre does exist, then I just need to create the association. 如果类型确实存在,那么我只需要创建关联即可。 Same for moods and tempos. 情绪和节奏也一样。

Thanks for any assistance. 感谢您的协助。

This seems to do it. 这似乎做到了。

1.upto @worksheet.last_row_index do |index|
  row = @worksheet.row(index)
  track = Track.find(row[0])
  genres = row[6].split(", ")
  genres.each do |g|
    track.genres << Genre.find_or_create_by_name(g)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM