我正在创建一个允许用户购买贺卡的商店(生日快乐,情人节)
我有两个模型:Card
和Recipient
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
并添加了自己的验证器。我只需要验证我的收件人(客户)信息。