【发布时间】:2023-03-05 14:37:02
【问题描述】:
我有这 2 个通过 habtm 关联的模型:
class Participant < ActiveRecord::Base
has_and_belongs_to_many :reports
end
和
class Report < ActiveRecord::Base
has_and_belongs_to_many :participants
end
在更新单个报告的视图中,可以输入参与者的电子邮件地址以将此参与者与当前报告相关联。
问题:通过在表单中删除他的电子邮件地址来删除参与者可以正常工作,但关联一个新的则不起作用(无论参与者本人是否已经存在)。
这是更新报告的代码:
num_of_participants = @report.participants.length
count = 0
num_of_participants.times do
if @report.participants[count].email.empty?
@report.participants[count].destroy
else
@report.participants[count] = Participant.find_or_create_by_email(@report.participants[count].email)
end
count += 1
end
@report.save!
任何帮助表示赞赏!
...这是我在这里的第一篇文章,希望没问题。
【问题讨论】:
标签: ruby-on-rails save new-operator has-and-belongs-to-many