I have a Group
model and a Message
model, each are HABTM. I'm trying to set a validation for my main form which is to send out a SMS to certain groups. Right now I have the body of message validated with presence: true
, that is working fine but in my Group model I want to validate name to be present but how to I have them both validate when I'm calling a create method in the messages controller? I'll show my code for more clarification.
Here is group.rb
class Group < ActiveRecord::Base
has_and_belongs_to_many :people
has_and_belongs_to_many :messages
validates :name, presence: true
end
Now message.rb
class Message < ActiveRecord::Base
has_and_belongs_to_many :groups
validates :body, presence: true
end
Here is my message_controller.rb
def create
@message = Message.create(message_params)
if @message.save
run_at_time = @message.send_at.present? ? @message.send_at : Time.zone.now
people = Person.in_groups(message_params[:group_ids])
if people.any?
people.each do |person|
person.delay(run_at: run_at_time).send_message(@message.body)
end
flash[:success] = "Messages on their way!"
end
redirect_to root_path
else
render "new"
end
end
For more understanding I want my form to display "Groups can't be blank" as well as "body can't be blank". If nothing is selected.