Suppose I have Post HABTM Tag and I am using mass asignment through nested attributes.
I have this in Post model:
accepts_nested_attributes_for :posts_tags, \
:reject_if => proc { |attrs| attrs.tag_id.blank? }
I have this in Post controller:
def new
@post = Post.new
3.times { @post.posts_tags.build }
end
def create
@post = Post.new(params[:post])
@post.save
end
And this in Post form:
<%= f.fields_for :tags do |tg| %>
<%= tg.label :tag_id %>
<%= tg.select :tag_id .... %>
<% end %>
Everything works just perfectly and with minimal code. The Post gets accociated with Tags that were selected.
And now: What if I want the users to select at least one Tag for their Post. How can I invalidate Post that has no Tag selected? What would be the most elegant solution?
Add
validates_presence_of :tagsin Post model to force the user to select the tag.