Rails嵌套表单,如果空白则拒绝,在编辑时删除记录

时间:2017-11-04 13:12:03

标签: ruby-on-rails

我有一个嵌套的表格“Letter”,与“消息”相关联,与“按钮”相关联。

这是我的Letter模型:

class Letter < ApplicationRecord
  validates :campaign_name, :presence => true

  belongs_to :core_bot
  has_many :messages, dependent: :destroy
  has_many :cards, dependent: :destroy, inverse_of: :letter
  has_many :filters, dependent: :destroy
  has_many :analytic_deliveries, dependent: :destroy
  has_many :analytic_reads, dependent: :destroy
  has_many :analytic_sends, dependent: :destroy


  accepts_nested_attributes_for :filters, allow_destroy: true, :reject_if => :all_blank
  accepts_nested_attributes_for :messages, allow_destroy: true, :reject_if => :all_blank
  accepts_nested_attributes_for :cards, allow_destroy: true, :reject_if => :all_blank
end

我的消息模型:

class Message < ApplicationRecord
  validates :content, :presence => true

  belongs_to :letter, optional: true
  has_many :buttons, dependent: :destroy

  accepts_nested_attributes_for :buttons, :reject_if => Proc.new { |att| att[:button_text].blank? && att[:button_url].blank? }, allow_destroy: true
end

如果“button_text”和“button_url”为空,我不想保存按钮条目。但是,在编辑时,如果创建了一个按钮并且用户想要删除它(“button_text”和“button_url”为空白),我希望能够删除该记录。

我该怎么做?我想过做一个after_action方法,但也许还有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

要仅在编辑时允许空白条目,请使用指定的操作向Button模型添加验证:  :allow_blank => true, on: :editbutton_text属性的button_url

此外,从:reject_if模型中移除Message语句,并验证on: :create上所有属性Button的存在。这样验证就不会相互干扰。

答案 1 :(得分:1)

要允许update包含空属性,您可以考虑将验证移至Button模型,如下所示:

validates_presence_of :button_url, on: :create

要删除recrod,只需允许用户通过添加delete操作的链接来删除“编辑”中的记录,如下所示:

# edit.html.erb
<%= link_to "Delete", button_path(@button), :confirm => "Are you sure?", :method => :delete %>