has-many-through create! validate presence

戏子无情 提交于 2019-12-11 09:09:46

问题


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?

I tried the following approaches:

  • 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

Any ideas?


回答1:


Use a callback

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

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.



来源:https://stackoverflow.com/questions/19951063/has-many-through-create-validate-presence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!