有很多通过创建!验证存在 [英] has-many-through create! validate presence

查看:41
本文介绍了有很多通过创建!验证存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型 User Item ,它们与 has_many通过关联相关.我想创建没有项目的用户,但是项目创建应验证至少一个用户的存在.我通过以下方式创建项目:

I have two models User and Item which are related with a has_many through association. I want to create users without items, but item creation should validate the presence of at least one user. I create items in the following way:

@user.items.create!(name: "Ball")

在创建商品之前,我该怎么做才能对用户的存在进行有效的验证?

What can I do to create a working validation of the presence of a user before creating the item?

我尝试了以下方法:

  • Item 模型中的 validate:users,状态:true
  • validate:item_users,状态:true Item 模型中
  • ItemUser 联接模型中的 validate:user,:item,presence:true
  • 使用私有函数对 Item 模型中的 validate:should_have_at_least_one_user 进行验证,该私有函数会执行 error.add(:base,'选择至少一个用户'),如果self.users.count<1
  • a validate :users, presence: true in the Item model
  • a validate :item_users, presence: true in the Item model
  • a validate :user, :item, presence: true in the ItemUser join model
  • a validate :should_have_at_least_one_user in the Item model with a private function that does error.add(:base, 'select at least one user') if self.users.count < 1

这些方法都没有奏效.我认为问题在于某种竞争状况,因为当我以以下方式创建商品时,某些验证确实有效.

None of these approaches had worked. I think the problem is some kind of race condition, because when I create items the following way, some of the validations did work.

@item.new(name: "Ball")
@item.users << @user
@item.save

有什么想法吗?

推荐答案

使用回调

在您的Item控制器中:

In your Item controller:

before_save :user_for_item_exists?


private
def user_for_item_exists?
  return nil if @item.users == nil
  return @item      
end

第二次返回有些冗长,您可以忽略它.然后,您可以保存@item或将其设置为nil.您可以确保在模型中未保存零.

2nd return is somewhat verbose, you can omit it. You then have either the @item to save or nil. You can make sure in your model, that nil is not saved.

这篇关于有很多通过创建!验证存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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