【问题标题】:rails3: <object>.save! doesn't associate new children in habtmrails3: <对象>.save!不会将新孩子与 habtm 联系起来
【发布时间】: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


    【解决方案1】:

    我对您使用 count 和 num_of_participants 感到有些困惑。无论如何,这就是我的做法:

    在你的更新视图中,你应该有一个这样声明的表单,对吧?

    # views/reports/edit.html.erb
    <%= form_for @report, :url => report_path(@report) do |f| -%>
    

    如果这样做,那么用于输入电子邮件的文本字段应如下所示:

    # views/reports/edit.html.erb
    <%= f.text_field :emails, :name => "emails[]" %>
    

    如果您使用的是form_tag 而不是form_for,那么您应该使用text_field_tag 而不是f.text_field

    你问为什么这样做?好吧,因为这样,您所有的电子邮件都将被包裹在params[:emails] 中。它们都将位于一个数组中,这使事情变得更加容易。

    现在,我们要做的第一件事是获取与报告关联的当前电子邮件,并将它们与我们从表单中获得的电子邮件进行比较。如果其中一封电子邮件已从表单中删除,我们应该将其从报告中删除。

    # controllers/reports_controller.rb
    @report.participants.each do |participant|
      if !params[:emails].include?(participant.email)
        @report.participants.delete(participant)  #remove the link to the participant from the report
      end
    end
    

    现在,我们需要遍历我们的 emails 数组,如果报告中没有使用该电子邮件的用户,请添加该参与者。

    # controllers/reports_controller.rb
    params[:emails].each do |email|
      participant = @report.participants.find_by_email(email)
      if participant.nil?
        @report.participants << Participant.find_or_create_by_email(email)
      end
    end
    

    就是这样!

    @report.save!
    

    【讨论】:

    • 谢谢伙计,这行得通。我有一个嵌套表单,所以我现在再使用一个循环将所有电子邮件地址放入一个数组中,然后按照您的建议继续。
    【解决方案2】:

    当您将对象分配给has_and_belongs_to_many 关联时,该对象会自动保存

    【讨论】:

    • 在我的情况下它没有,不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多