嵌套表单验证

时间:2013-08-04 21:04:21

标签: ruby-on-rails validation

提交后的表单不会检查嵌套模型上的验证。即使我没有在:value的表单中的文本字段中添加任何值,它仍会保存联系人卡片,然后使用root_path重定向到:notice。当我输入好的数据时,表单按照我期望的方式工作并填充值。

任何指针都会非常感激。

父模型的控制器:

class ContactCardsController < ApplicationController

  def create

    @contact_card = ContactCard.new(params[:contact_card])

      if @contact_card.save
        redirect_to root_path, notice: "Contact Card Added To Directory!"
      else
        redirect_to new_path, alert: "not saved"
      end

  end

  def new
    @directory = Directory.find(params[:directory_id])
    @contact_card_field_templates = @directory.contact_card_field_templates
    @contact_card_fields = []
    @contac_card = nil

    if(cookies[:cc_id].blank?)
      @contact_card = ContactCard.new(directory_id: @directory.id)
      cookies[:cc_id] = @contact_card.id
      if(!user_signed_in?)
        @contact_card_field_templates.each do |ccft|
          @contact_card_fields.push(ContactCardField.new(field_label: ccft.name, required:     ccft.required, contact_card_id: @contact_card.id))
        end
      else
        @contact_card_field_templates.each do |ccft|
          @contact_card_fields.push(User.contact_card_fields.where("field_label = ?", ccft.name).first)
        end
      end
      @contact_card.contact_card_fields = @contact_card_fields
    else
      @contact_card = ContactCard.find(cookies[:cc_id])
      @contact_card_fields = @contact_card.contact_card_fields
    end

  end
end

我的父母模特:

class ContactCard < ActiveRecord::Base
  attr_accessible :contact_card_fields_attributes, :user_id, :directory_id

  belongs_to :directory
  belongs_to :user
  has_many :contact_card_fields

  accepts_nested_attributes_for :contact_card_fields, allow_destroy: true, reject_if: proc { |attributes| attributes['value'].blank?}
end

我的孩子模特:

class ContactCardField < ActiveRecord::Base
  attr_accessible :field_label, :required, :value, :user_id, :contact_card_id

  belongs_to :contact_card
  belongs_to :user

  validates_presence_of :value

end

在 我正在使用的表格:

- if @contact_card.errors.any?
  #error-explanation
    h2
      =pluralize @contact_card.errors.count, "error"
      = " prohibited this record from being saved:"
      ul
        - @contact_card.errors.full_messages.each do |msg|
          li
            =msg

=form_for @contact_card do |f|
  - if !user_signed_in? || !@directory.current_user_admin?(current_user)
    =f.fields_for :contact_card_fields do |builder|
          =builder.label builder.object.field_label
          =builder.text_field :value

    =f.submit "Create Contact Card"

1 个答案:

答案 0 :(得分:1)

我非常确定首先检查reject_if,因此如果用户添加ContactCardFieldvalue,则在尝试保存联系之前,它已被拒绝保存将始终有效。

选项:

  • ContactCard上添加至少应存在一个ContactCardField的验证(如果您的情况需要)
  • 删除reject_if的{​​{1}}子句,让模型中的验证完成其工作。