Validating presence of a tag


#1

Hi,

I’m using acts_as_taggable. I have a form that asks for a question and a
tag
for that question, something like:

<% form_tag -%>
<%= text_area(“question”, “question_text”) %>
<%= text_field(“tag”, “name”) %>
<%= submit_tag %>
<% end_form_tag %>

The question is one model. Tag is another.

My problem is that I can’t figure out how to validate that the user
inputs a
tag. He must input both a question and a tag.

My controller method looks something like:

def add_question
if request.get?
@question = Question.new
@tag = Tag.new #needed this so my errors_messages_for :tag will
not
cause error
else
@question = Question.new(params[:question])
if @question.save
@question.tag(@params[:tag][:name])
flash[:notice] = “Thank you. Your question has been
added.”
redirect_to edit_url(@question.id)
end
end
end

I tried nesting a transaction for both question and tag, but that didn’t
work. I tried various ways of passing the tag names into the
@question.tagmethod.

My validations include:

Class Question < ActiveRecord Base
validates_presence_of :question_text, :message=>“must not be blank.”
validates_length_of :question_text, :maximum=>150, :message=>“must be
less
than 150 characters.”
end

Class Tag < ActiveRecord Base
validates_presence_of :name
validates_length_of :name, :in => 1…20, :too_long => "Tag name too
long

  • max 20 characters", :too_short => “Tag must have a name”

end

Suggestions are appreciated.

Steve
http://www.smarkets.net