创建与.build的关联并解决参数validation问题

使用Rails 3.2.9
我正在尝试使用.build而不是.create构建一个关联,但是获得了一个密码validation错误,我似乎无法找到解决方法。
点评如下:

我理解的方法是保存一个使用.build构建的关联的项目,你实际上必须在这个案例中对所有者进行保存。 如果你在@item上进行保存,它只是创建项而不是关联(意味着它不会保存到DB,直到current_owner.save)。 当我对所有者进行保存时,由于密码不符合validation要求,我遇到了错误。 有没有办法在我进行保存时绕过validation,因为我需要为密码实现不同的解决方案,或者只是停止抱怨并使用.create而不是.build。

下面给出的密码不符合validation错误

@item = current_owner.items.build(params[:item]) if current_owner.save Do some other work with item end 

我想我可以做以下事情(出于某种原因,它似乎对我来说可能不是。想法?)

  @item = current_owner.items.create(params[:item]) if !@item.nil? Do some other work with item end 

表设置:所有者:

  • ID
  • 名称
  • encrypted_pa​​ssword

项目:

  • ID
  • 名称

items_owners:

  • owner_id
  • ITEM_ID

楷模:

 class Item  :items_owner end class Owner  :items_owner before_save :encrypt_password validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 } end class ItemsOwner < ActiveRecord::Base attr_accessible :owner_id, :item_id belongs_to :item belongs_to :owner end 

我不太了解你的问题。 希望这可以帮助:

 @item = current_owner.items.build(params[:item]) if @item.valid? # item is valid and ready to save to DB else # item is not valid. end 

您的模型中有密码validation,需要密码存在。 你可以做的是如下

 @item = current_owner.items.build(params[:item]) if @item.valid? @item.save # do stuff what you want else # item is not valid. end 

希望它会有所帮助