0

I have a Post model and Comment model (Post has_many comments, Comment belongs_to Post)

I want to validate a field in my Comment model where they can only create/update if a comment field is less than the difference between 2 Post date_fields. How do I go about achieving this?

Right now, in my Comment model, I have:

validates :comment_check, presence: true, :numericality => { :greater_than_or_equal_to => 0 }

I just need to add the validation to make it :less_than_or_equal_to the Post date diff. I also have this model method in my Post model:

def self.days_diff
  (end_date.to_date - start_date.to_date).to_i
end

Any help would be greatly appreciated!

1 Answer 1

1

In your Comment Model you can validate with:

validate :comment_date

def comment_date
  if self.post.end_date < Time.now or self.post.start_date.to_date > Time.now
    self.errors.add(:created_at, "failed to save at the moment")
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

awesome! I adjusted a few of the variable names, but syntax was spot on. Thanks JB!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.