Question

I'm writing a Redmine plugin and added some fields to issues form via hooks (the fields are also added to Issue table), so far so good. Now I want to make those fields mandatory, but can't figure out how to 'override' validates_presence_of behavior for Issue model.

I've created a hook for Issue save method, in order to check presence of my new fields before saving, but not sure if this is the best way to go. Is it possible to just extend Issue model so that it validates for presence of my new fields?

Was it helpful?

Solution

You can add validations on new fields in you plugin. Example is here

# load plugin file(s)
Rails.configuration.to_prepare do
  TimeEntry.send(:include, TimeLimitTimeEntryPatch)
end



# in patch file
module TimeLimitTimeEntryPatch
  def self.included(base)

    base.send(:include, InstanceMethods)

    base.class_eval do
      unloadable

      validates_presence_of :comments
      validate :validate_time_limit_allowed_ip

    end

  end

  module InstanceMethods

    def validate_time_limit_allowed_ip
      # add error if permission is not set and IP is not allowed
      if !self.class.have_permissions?(user, project) && !time_limit_allowed_ip
        errors.add(:hours, I18n.t(:not_allowed_ip))
      end
    end

  end

end

OTHER TIPS

Alternatively:

1) Create extension somewhere in your lib directory (make sure that it is required):

module IssueExtensions
  extend ActiveSupport::Concern

  included do
    validates_presence_of :new_attr
  end

end

2) Send it to Issue model. Good place for this could be config/initializers/extensions.rb (must be initialized after Redmine obviously):

Issue.send(:include, IssueExtensions)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top