Reputation: 116
I have Meets model meet.rb with one attribute called tags. User inputs them with single form_for. Question would be: how can I limit in my model that if user inputs more that 3 words, he would get an error message. Or if you can show me solution with javascript it would be nice too. Thank you!
Upvotes: 0
Views: 103
Reputation: 44360
it's best to check on the client side
create word_couter.js.coffee
in app/assets/javascripts
include to app/assets/javascripts/application.js.coffee
this file #= require word_couter
$ ->
$('[name="you_input"]').on "change", ->
input_size = $(@).val().split " "
if input_size.length > 3
...some code here ....
I hope this help!
Upvotes: 0
Reputation: 51151
I would probably write custom validation method in Meet
model:
class Meet < ActiveRecord::Base
# ...
validate :no_more_than_three_tags
# ...
def no_more_than_three_tags
errors.add(:tags, 'more than three words') if tags.split(/\W/).count > 3
end
end
Upvotes: 3
Reputation: 5999
Without any code to go off of, I would think you have a method with an argument, tags. If so, you might do something like this.
def method(tags)
array = tags.split(" ")
raise ArgumentError.new("More than three words entered") if array.size > 3
end
Upvotes: 0