创建与 .build 的关联并解决参数验证 [英] Creating association with .build and working around parameter validation

查看:63
本文介绍了创建与 .build 的关联并解决参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 3.2.9
我正在尝试使用 .build 而不是 .create 来建立关联,但收到密码验证错误,我似乎找不到解决方法.
评论如下:

Using Rails 3.2.9
I'm attempting to build a association using .build instead of .create but getting a password validation error that I can't seem to find a workaround.
Review below:

据我所知,使用 .build 构建的关联保存项目的方式实际上必须在这种情况下对所有者进行保存.如果您对@item 进行保存,它只会创建项目而不是关联(这意味着它在 current_owner.save 之前不会保存到数据库中).当我对所有者进行保存时,由于密码不符合验证要求而出错.有没有办法在我保存时绕过验证,因为我需要为密码实施不同的解决方案,或者只是停止抱怨并使用 .create 而不是 .build.

The way I understand to save a item with a association that is built using .build you actually have to do the save in this case on the owner. If you do a save on the @item it just creates the item and not the association(meaning it doesn't save to the DB until current_owner.save). when i do a save on the owner i hit a error due to password not meeting the validation requirements. Is there a way to bypass the validation when I do a save, due i need to implement a different solution for password, or just stop complaining and use .create instead of .build.

下面给出密码不符合验证错误

The below gives a password does not meet validation error

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

我想我可以执行以下操作(出于某种原因,这对我来说似乎很脏,也许不是.想法?)

I guess i could do the following(for some reason it seems dirty to me maybe not. Thoughts?)

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

表设置:业主:

  • id
  • 姓名
  • encrypted_pa​​ssword

项目:

  • id
  • 姓名

items_owners:

items_owners:

  • owner_id
  • item_id

型号:

class Item < ActiveRecord::Base
   attr_accessible :description, :name, :owner_ids

   has_many :items_owner
   has_many :owners, :through => :items_owner


end

class Owner < ActiveRecord::Base
   attr_accessor :password
   attr_accessible :name, :password, password_confirmation

   has_many :items_owner
   has_many :items, :through => :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

推荐答案

我不太明白你的问题.希望这会有所帮助:

I didn't understand very much your question. Hope this helps:

@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

这篇关于创建与 .build 的关联并解决参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆