开发者

Is there a way to validates_presence_of only one time? (to skip that validation once the user's been notified)

开发者 https://www.devze.com 2022-12-25 06:10 出处:网络
So, I\'d like for a user to see an error message if he submits a comment and the :name is blank (typical error message, don\'t need help with that).However, I\'d then like to allow the user to skip th

So, I'd like for a user to see an error message if he submits a comment and the :name is blank (typical error message, don't need help with that). However, I'd then like to allow the user to skip that validation once he's been notified that "we like all comments to have a name." So, he submits the comment once, sees the notification, then can submit the form again unchanged if he really doesn't want to add a name, and the validates_presences_of :name is skipped.

But, I'm not sure how to go about doing this. I thought about checking to see where the request is coming from, but after a create, errors are handed off to the "new" action, which is the same as actual "new" comments.

I then thought about checking to see if flash[errors] were present, but that won't work because there are other validations a comment has to pass.

Finally, I thought about trying a

validates_presences_of :name, :unless => :notified

but wasn't sure how to define notified. I honestly hate asking such an open ended question, but wasn't sure where to get started. So, is there a way to just check a certain validation once?

Edit: here's my controller

@comments = params[:comments].values.collect{ |comment| current_user.comments.create(comment) }.reject { |p| p.errors.empty? }

and my view:

<% @comments.each_with_index do |comment, index| %>
   <% fields_for "comments[#{index}]", comment do |f| %>
      <%= render :partial => 'form', :locals => { :f => f } %>
   <% end %>
<% end %>

(the stuff in the 'form' partial is just the basic f.label, f.text_area stuff开发者_如何学Python)

I'm thinking the problem is really in my view, since it handles an array of comments. Should the notified hidden field be defined in the 'form' partial, or in this "new" view? My thinking is that each iteration of the partial doesn't need a notified hidden_field, but only the overall form itself. But then again I don't know.


Your solution should work fine. Just add attr_accessor :notified to the model, and add a hidden field for it in the form: form.hidden_field :notified. Then, in the controller action, if validations fail, set @comment.notified = true before re-displaying the view.

Edit: Yeah, with multiple comments it is probably easier to just do

@notified = true

in the controller else statement, and then add

<%= f.hidden_field :notified, :value => @notified %>

to the form partial. Then, each comment will have notified set to true and will skip that validation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号