I have a Post Model, and a comment Model. I would like to limit the comments to 3. How would you do this?
Would it be best to create a validation? If so what would this look like?
Would you do this in the view unless Post.comments == 3
?
Would a callback make sense?
the post's comments count validation is the "Comment" model responsibility, so I'd like to suggest the following code:
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
You should always validate at the model level as well as the views.
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
Then just call #commentable?
in your views like this. You should never hard-code values in the views.
<% if @post.commentable? %>
<%= render "form" %>
<% end %>
I would make sure not to let them submit that fourth comment that you don't want to allow. Some might say you should do the check in your controller and pass a flag, but for something this simple the check in the view seems fine.
Validate it in the models. You could use validates_with
as described here .
In the view, you'd be better off checking with an inequality like
unless Post.comments.length >= 3
show_form
end
That way if you have four comments for some reason (race condition or an admin posts a response after 3, etc.) the form stils won't show up.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.