2012-12-18 36 views
0

假設我有Post HABTM Tag,並且我通過嵌套屬性使用mass asignment。Rails,嵌套的屬性,無效的父母沒有子女

我有這個在Post模型:

accepts_nested_attributes_for :posts_tags, \ 
           :reject_if => proc { |attrs| attrs.tag_id.blank? } 

我有這樣的帖子控制器:

def new 
    @post = Post.new 
    3.times { @post.posts_tags.build } 
end 

def create 
    @post = Post.new(params[:post]) 
    @post.save 
end 

而這帖子的形式:

<%= f.fields_for :tags do |tg| %> 
    <%= tg.label :tag_id %> 
    <%= tg.select :tag_id .... %> 
<% end %> 

一切正常,只是完美,用最少的代碼。郵政與被選中的標籤相關聯。

現在:如果我希望用戶至少爲其帖子選擇一個標籤,該怎麼辦。我如何使帖子沒有選擇標籤失效?什麼是最優雅的解決方案?

回答

1

在Post模式中添加validates_presence_of :tags以強制用戶選擇標籤。

+0

就是這樣!謝謝。 –