为什么我的Rails Custom Validator不起作用?

时间:2014-12-03 18:08:06

标签: ruby-on-rails validation

我正在创建一个允许用户购买贺卡的商店(生日快乐,情人节)

我有两个模型:CardRecipient

class Card < ActiveRecord::Base

  belongs_to :recipient

  def valid_name
    if @recipient && @recipient.name.nil?
      @card.errors.full_messages.push("Name can't be blank")
    end
  end

  validate :valid_name
  validates_associated :recipient
  validates :recipient, presence: true
  validates :note, length: { in: 1..200 }

class Recipient < ActiveRecord::Base

  has_one :card

  validates :name, presence: true

end

卡控制器

def new
  @card = Card.new
  @card.build_recipient                                   
end

def create
  @card = Card.new(card_params)
  if @card.save
    flash[:notice] = "Your card was successfully added to your cart!"
    redirect_to :back
  else
    flash[:danger] = "Something was wrong"
    render 'new'
  end
end

PARAMATERS

def card_params
  params.require(:card).permit(:note, :amount, :recipient_attributes:[:name, :email])
end

我没有RecipientsController,但我认为我不需要。{/ p>

我想在购买卡片的表格中验证Recipients模型中的字段。

我尝试了validates_associated并添加了自己的验证器。我只需要验证我的收件人(客户)信息。

0 个答案:

没有答案