In my Rails app I have Content, Fields, and FieldContents.
The associations are:
class Content < ActiveRecord::Base
has_many :field_contents
end
class Field < ActiveRecord::Base
has_many :field_contents
end
class FieldContent < ActiveRecord::Base
belongs_to :content
belongs_to :field
end
Fields contain columns that describe the field, such as name, required, and validation.
What I want to do is validate the FieldContent using the data from its Field.
So for example:
class FieldContent < ActiveRecord::Base
belongs_to :content
belongs_to :field
# validate the field_content using validation from the field
validates :content, presence: true if self.field.required == 1
validates :content, numericality: true if self.field.validation == 'Number'
end
However I'm currently getting the error: undefined method 'field' for #<Class:0x007f9013063c90>
but I'm using RubyMine and the model can see the association fine...
It would seem self
is the incorrect thing to use here! What should I be using?
How can I apply the validation based on its parent values?