sites
sites

Reputation: 21795

Validate Rails model just when some method is called

For some reason I need to run this validation

validates_presence_of :user_id

just when some method is called

def publish # this method does not save nor update record
            # so validations are not run
  ...
end

I have solved it this way:

# model
validates_presence_of :user_id, if: :going_to_publish
attr_accessor :going_to_publish

# when calling publish
post.going_to_publish = true
post.publish

Is there a way to remove that flag variable?

Upvotes: 2

Views: 647

Answers (1)

Billy Chan
Billy Chan

Reputation: 24815

I don't see any necessity here.

If you publish a post, the post obj must be persistent. So the publish method must call create/save method inside.

If such methods called, the validation rules will be called as well.

add

Validation works for update as well

Creating and saving a new record will send an SQL INSERT operation to the database. Updating an existing record will send an SQL UPDATE operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation.

http://guides.rubyonrails.org/active_record_validations_callbacks.html#when-does-validation-happen

Upvotes: 1

Related Questions