class Organisation < ActiveRecord::Base has_many :people has_one :address,:as => :addressable,:dependent => :destroy accepts_nested_attributes_for :address,:allow_destroy => true end class Person < ActiveRecord::Base attr_accessible :first_name,:last_name,:email,:organisation_id,:address_attributes belongs_to :user belongs_to :organisation has_one :address,:allow_destroy => true # These two methods seem to have no effect at all! validates_presence_of :organisation,:unless => "address.present?" validates_associated :address,:unless => "organisation.present?" end class Address < ActiveRecord::Base belongs_to :addressable,:polymorphic => true validates_presence_of :line1,:line2,:city,:zip end
……以及这些观点:
_fields.html.erb:
<%= render 'shared/error_messages',:object => f.object %> <fieldset> <div class="left"> <%= f.label :first_name %><br/> <%= f.text_field :first_name %> </div> <div> <%= f.label :last_name %><br/> <%= f.text_field :last_name %> </div> <div> <%= f.label :email %><br/> <%= f.text_field :email %> </div> <div> <%= f.label :organisation_id %><br/> <%= f.select(:organisation_id,current_user.organisation_names,{:include_blank => "--- None ---"},:id => 'organisation_select') %> </div> </fieldset> <%= f.fields_for :address do |address| %> <%= render 'shared/address',:f => address %> <% end %>
_address.html.erb:
<fieldset id="address_fields"> <div> <%= f.label :line1 %> <%= f.text_field :line1 %> </div> <div> <%= f.label :line2 %> <%= f.text_field :line2 %> </div> <div> <%= f.label :zip %> <%= f.text_field :zip %> </div> <div> <%= f.label :city %> <%= f.text_field :city %> </div> </fieldset>
people_controller.rb:
def new puts params.inspect @person = Person.new(:organisation_id => params[:organisation_id]) @person.build_address @title = "New person" end {"action"=>"new","controller"=>"people"} def edit puts params.inspect @title = @person.name end {"action"=>"edit","id"=>"69","controller"=>"people"} def create puts params.inspect if params[:organisation_id] @person = current_user.organisations.build_person(params[:person]) else @person = current_user.people.build(params[:person]) end if @person.save flash[:success] = "Person created." redirect_to people_path else render :action => "new" end end {"commit"=>"Create","action"=>"create","person"=>{"last_name"=>"Doe","organisation_id"=>"9","email"=>"john.doe@email.com","first_name"=>"John","address_attributes"=>{"city"=>"Chicago","zip"=>"12345","line2"=>"Apt 1","line1"=>"1 Main Street"}},"authenticity_token"=>"Jp3XVLbA3X1SOigPezYFfEol0FGjcMHRTy6jQeM1OuI=","controller"=>"people","utf8"=>"✓"}
在我的Person模型中,我需要确保只有当一个人的organisation_id为空时,该人的地址字段必须存在.
我试过这样的事情:
validates :address,:presence => true,:if => "organisation_id.blank?"
但它不起作用.
如何才能做到这一点?
谢谢你的帮助.
解决方法
validate :address,:presence_of => true,:if => 'organisation.present?'
意思是,如果组织也存在,您只想验证地址.
关于,:accepts_nested_attributes_for,你是通过传入嵌套的表单属性,还是某些这样的东西来使用这个功能的?我只是想确保你绝对需要使用这个功能.如果您实际上没有处理嵌套表单属性,则可以使用以下方法实现级联验证:
validates_associated :address
如果确实需要使用:accepts_nested_attributes,请务必查看:reject_if参数.基本上,如果某些条件适用,您可以完全拒绝添加属性(及其后代):
accepts_nested_attributes_for :address,:allow_destroy => true,:reject_if => :no_organisation def no_organisation(attributes) attributes[:organisation_id].blank? end
现在,如果以上都不适用,那么让我们来看看你的语法:
它应该工作,:if /:除非取symbols,strings and procs.你不需要指向foreign_key,但可以通过指向以下内容来简化:
:if => "organisation.blank?"
您在地址模型中有其他验证,对吗?地址是否在您不想要的时候被验证?或者地址未经过验证?如果你能给我一些额外的细节,我可以帮你在控制台测试一下.
>为了让自己更轻松:重量分配,我更改了rails config:config.active_record.whitelist_attributes = false
>我创建了a gist for you to follow along
>我也有一个示例项目.如果您有兴趣,请告诉我.
基本要点:
>向Person添加以下内容以确保Org或Address有效:
validates_presence_of:organization,:unless => “address.present?”
validates_associated:address,:unless => “organisation.present?”
>在地址中添加了验证,以便在Org不存在时触发错误:
validates_presence_of:line1,:line2,:city,:zip
我能够满足您的要求.请查看at the gist I created,我有一个完整的控制台测试计划.
我加了a controller file to the previous gist.
概述:
>你需要创造的人是:
@person = current_user.people.build(params [:person])
>:organisation_id将永远位于:person param节点之外,如下所示:
PARAMS [:人] [:organisation_id]
所以你永远不会是真的.
我通过对the controller,the model和the form的必要更改更新了要点.
概述:
>您需要清理控制器.你正在使用accepts_nested_attribute,所以在:create中,你只关心params [:person].此外,在render:new中,您需要设置partial将使用的任何实例变量.这不会通过:新动作返回. :new和:edit操作也需要简化.
>您的Person模型需要使用:reject_if参数,因为Address字段将返回到:create action as:address_attributes => {:line1 => ”,:line2 => ”,等等.你只想创建关联,如果有任何值.那么你的validates_presence_of for:organization就可以了.
>您的表单需要将组织ID传递给控制器,而不是组织名称
一切都在the gist
应该是the final gist.
概述:
@ person.build_address if @ person.address.nil?
这确保您具有地址输入,即使@ person.address不存在也是如此.它不存在,因为在accepts_nested_attributes上有:reject_if条件
>我干掉了:reject_if,如下所示.这有点hacky,但有一些实用性:
accepts_nested_attributes_for :address,:reject_if => :attributes_blank? def attributes_blank?(attrs) attrs.except('id').values.all?(&:blank?) end
一个. attrs – > params [:person] [:地址]的结果湾.except(‘id’) – >返回除“id”之外的所有键值C. .values – >将散列中的所有值作为数组返回d. .所有? – >数组中的所有元素是否满足以下检查即& ;: blank – >一个块的ruby简写,像这样:全部?{| v | v.blank? }