Validate presence of nested attributes within a form

北城余情 提交于 2019-12-05 15:57:47
Neil

This does the validations for both creating and updating a contact: making sure there is at least one associated contacts_team. There is a current edge case which leads to a poor user experience. I posted that question here. For the most part though this does the trick.

#custom validation within models/contact.rb
class Contact < ActiveRecord::Base
  ...
  validate :at_least_one_contacts_team

  private
  def at_least_one_contacts_team
    # when creating a new contact: making sure at least one team exists
    return errors.add :base, "Must have at least one Team" unless contacts_teams.length > 0

    # when updating an existing contact: Making sure that at least one team would exist
    return errors.add :base, "Must have at least one Team" if contacts_teams.reject{|contacts_team| contacts_team._destroy == true}.empty?
  end           
end
Vasu

In Rails 5 this can be done using:

validates :contacts_teams, :presence => true

If you have a Profile model nested in a User model, and you want to validate the nested model, you can write something like this: (you also need validates_presence_of because validates_associated doesn't validate the profile if the user doesn't have any associated profile)

class User < ApplicationRecord

  has_one :profile
  accepts_nested_attributes_for :profile
  validates_presence_of :profile
  validates_associated :profile

docs recommend using reject_if and passing it a proc:

accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Model Names: 1: approval 2: approval_sirs

Associations: 1: approval has_many :approval_sirs, :foreign_key => 'approval_id', :dependent => :destroy accepts_nested_attributes_for :approval_sirs, :allow_destroy => true 2: approval_sirs
belongs_to :approval , :foreign_key => 'approval_id'

In approvals.rb ## nested form validations validate :mandatory_field_of_demand_report_sirs

private

def mandatory_field_of_demand_report_sirs
    self.approval_sirs.each do |approval_sir|
        unless approval_sir.marked_for_destruction?
          errors.add(:base, "Demand Report Field are mandatory in SIRs' Detail") unless approval_sir.demand_report.present?
        end
    end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!