Validating length of habtm association without saving

荒凉一梦 提交于 2019-12-05 09:42:25

You had two problems here:

  1. You're overriding validations
  2. The order of operations in saving is causing problems.

You're overwriting the validate method which is a bad thing, because the built in behaviour to deny records with validation errors to be saved to the database. To add custom validations you want to do this:

validate :maximum_group_length

def maximum_group_length
    if self.groups.length > 5
        self.errors.add(:groups, "cannot have more than 5 groups")
    end
end

However, the nature of HABTM relationships requires you to do it as an after_save callback. Just because of the order that things are done. user.groups is based on the implicit join table and there for isn't updated until the join table is updated.

If you're trying to validate as part of a callback (before_save, after_creation, etc.), then adding an error to the object won't trigger a roll back. Callbacks will only trigger a rollback if they return false. This will handle the after save implementation the question suggest.

after_save :validate_maximum_group_length

def validate_maximum_group_length
    if self.groups.length > 5
        self.errors.add(:groups, "cannot have more than 5 groups")
        return false
    end
end

Another solution is to use an explicit join model. And a has_many :through relationship. The join model's table is updated in the update statement. Where as the has_many :through and HABTM relationships update the relationship after the save.

class User < ActiveRecord::Base
  has_many :user_groups
  has_many :groups, :through => user_groups, allow_destroy

  validate :max_group_length
    errors.add(:groups, "cannot have more than 5 groups") if self.user_groups.length > 5
  end

end

class UserGroup < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end

HABTM implicitly uses a join table, so it doesn't need to be changed on the group side.

However you will need to modify your form to update the form to supply group_id in the params hash as params[:user][:user_group_attributes][0][:group_id][3]

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