问题描述:

Here is my Rail4 app: the app will have many services, and each service may have many submissions. A submission can be either a picture, or a word file, or a pdf file. However, the content type of a submission is really defined by the service object.

I understand there is a validates_attachment_content_type function, but the question is how can I dynamically change the content_type according to the service object?

Here is the code for my project:

class Service < ActiveRecord::Base

attr_acccessor :service_content_type

has_many :submissions

end

class Submission < ActiveRecord::Base

belongs_to :service

has_attached_file :attachment

validates_attachment_content_type :attachment,

:content_type => self.service.service_content_type # THIS LINE IS NOT WORKING

end

网友答案:

One problem is that the validation is declared in the class context. self here refers to the class, not the instance, so calling self.service would raise an error since service is an instance method.

ActiveModel validations usually let you pass in a lambda block in which you can use the instance to determine validity. But the Paperclip doc says validates_attachment_content_type only lets you pass in a String, Regexp, or an Array containing elements of the those two types.

You can use a custom validation method to make sure your attachment_content_type column is the right value. But I'm not 100% sure if this offers the same security as validates_attachment_content_type.

class Submission < ActiveRecord::Base
  belongs_to :service

  has_attached_file :attachment

  validate :validate_content_type

  def validate_content_type
    unless attachment_content_type == service.service_content_type
      errors.add(:attachment_content_type, "must be #{service.service_content_type}")
    end
  end
end

Or you can use a built-in Rails validation with a lambda but have less control over the error message:

  validates :attachment_content_type,
    inclusion: { in: ->(submission) { [submission.service.service_content_type] } }
网友答案:

self.service.service_content_type has to be regex, which I am guessing isn't. Read doc

相关阅读:
Top