2011-07-25 38 views
1

我有一個發佈模型和評論模型。我想將意見限制爲3.您如何做到這一點?導軌設計問題

  1. 是否最好創建一個驗證?如果是的話,這看起來像什麼 ?

  2. 你會在視圖unless Post.comments == 3這樣做嗎?

  3. 回調是否有意義?

回答

4

這篇文章的評論數驗證「註釋」模式的責任,所以我想建議將以下代碼:

class Comment < ActiveRecord::Base 
    belongs_to :post 

    before_create :limit_number 

    private 
    def limit_number 
    if post.comments.count >= 3 
     errors.add(:post, "the limit of comments is over") 
    end 
    end 
end 

class Post < ActiveRecord::Base 
    has_many :comments 
end 
+0

提供意見的功能,你可以使用一個輔助方法 – Anatoly

1

我會確保不讓他們提交你不想讓第四條評論。有人可能會說你應該在你的控制器中做檢查並通過一個標誌,但是對於這個簡單的事情來說,視圖中的檢查看起來很好。

0

在模型中進行驗證。您可以使用validates_with,如here所述。

在視圖中,你會更好用不平等

unless Post.comments.length >= 3 
    show_form 
end 

這樣檢查,如果你有四條意見出於某種原因(競爭條件或管理崗位的響應3後,等等)窗體stils不會出現。

3

您應該始終在模型級別以及視圖上進行驗證。

class Comment < ActiveRecord::Base 

    belongs_to :post 
    validate :check 

    private 

    def check 
    if post.present? 
     errors.add("Post", "can not have more than 3 comments") if post.comments.size >= 3 
    end 
    end 

end 

class Post < ActiveRecord::Base 
    # other implementation... 

    def commentable? 
    comments.size <= 3 
    end 

end 

然後只需在您的意見中調用#commentable?就可以了。你不應該在視圖中硬編碼值。

<% if @post.commentable? %> 
    <%= render "form" %> 
<% end %>