How to checkbox validation in Ruby on Rails?

Asked

Viewed 149 times

0

I’m studying ruby on Rails and little time, and one of the exercises I’m trying to do is a checkbox and a Submit button on a haml page, the goal is that the Submit button only works if the checkbox is marked, if it doesn’t just give a generic message like "Complete the fields", how can I do this?

1 answer

1


Rails has a validator called acceptance_of. It is used when you have a boolean and want to check if this value is true.

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: true
end

See more Rails validations on documentation.

When you call model.save, check the following:

if person.save
  # successo!
else
  # erro :(
  person.errors.full_messages
  # => [ { terms_of_service: "must be accepted" }]
end
  • On the Submit button itself I need to pass the value of Acceptance? or on the checkbox? Just need the model and controller? I haven’t quite got the hang of it yet

  • @dfop02 on the model

Browser other questions tagged

You are not signed in. Login or sign up in order to post.