问题
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 theItem
model - a
validate :item_users, presence: true
in theItem
model - a
validate :user, :item, presence: true
in theItemUser
join model - a
validate :should_have_at_least_one_user
in theItem
model with a private function that doeserror.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