用下面的关联:验证存在从另一个模型
class Profile < ActiveRecord::Base
belongs_to :visitor
belongs_to :contact_point
validates :contact_point, presence: true
end
class Visitor < User
has_one :profile, dependent: :destroy
has_one :contact_point, through: :profile
end
class ContactPoint < User
has_many :profiles
has_many :visitors, through: :profiles
end
每个ContactPoint
有一个电子邮件。当访问者使用以下表单创建其个人资料时,她需要使用属于ContactPoint
的电子邮件地址确定个人资料联系点。联系点用户已创建,访问者不应该能够更新ContactPoint
模型。
<%= form_for @profile do |f| %>
<%= f.label 'First Name' %>
<%= f.text_field :first_name %>
<%= f.label 'Last Name' %>
<%= f.text_field :last_name %>
<%= fields_for :contact_point, @profile.contact_point do |ff| %>
<%= ff.label 'Contact point email' %>
<%= ff.text_field :email %>
<% end %>
<% end %>
在ProfilesController
我传递的参数来分析这样的模型:当没有ContactPoint
提供的电子邮件地址
def create
@profile = Profile.create(profile_params)
end
def profile_params
contact_point = ContactPoint.find_by_email(params[:contact_point][:email])
params.require(:profile).permit(:first_name, :last_name)
.merge(visitor_id: current_user.id, contact_point: contact_point)
end
通过以上的设置,该contact_point
变量设置为nil
验证人无法区分填写的联系人电子邮件是否为空。 现在,我如何添加验证以检查contact_points
表中此电子邮件地址的存在并显示自定义错误消息?
'验证:contact_point,存在:TRUE'应该做的伎俩。你确定记录正在保存到数据库吗? –
问题是,contact_point = ContactPoint.find_by_email(params [:contact_point] [:email])'设置contact_point_id为零,当这个电子邮件地址没有contact_point时。 contact_point_id将为零的其他情况是当发布表单中该字段为空时。我需要验证者来隔离这两个案件。 – Sajjad