Validate dependent model validation and show error message.
- by piemesons
Just taking a simple example.
We have a question on stackoverflow and while posting a question we want to validate title_of_question, description_of_question that they should be present. Now we have a another model tag having habtm relationshio with question model. How to validate that while saving the question. Means question must have some tags.
here the code:--
Models:--
class Question < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :tags
has_many :comments, :as => :commentable
has_many :answers, :dependent => :destroy
validates_presence_of :title, :content, :user_id
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :questions
validates_presence_of :tag
end
Form for entering question and tag
<div class="form">
<% form_for :question ,@question, :url => {:action => "create" } do |f| %>
<fieldset>
<%= f.error_messages %>
<legend>Post a question</legend>
<div>
<%= f.label :title %>:
<%= f.text_field :title, :size => 100 %>
</div>
<div>
<%= f.label :content ,'Question' %>:
<%= f.text_area :content, :rows => 10, :cols => 100 %>
</div>
<div>
<%= label_tag 'tags' %>:
<%= text_field_tag 'tag' ,'',:size=> 60 %> add multiple tag using comma
</div>
<div>
<%= submit_tag "Post question" %>
</div>
</fieldset>
<% end %>
</div>
From Controller.. (Right now question will be saved without validating tag)
def create
@question = Question.new(params[:question])
@question.user_id=session[:user_id]
if @question.save
flash[:notice] = "Question has been posted."
redirect_to question_index_path
else
render :action => "new"
end
end
questions_tags table has been created.
One approach is creating a virtual column using attribute accessors.
another approach is validate associated.
right now assuming new tags can be created.(but not duplicate).