如果存在params,则为validate_presence_of field_name

时间:2013-02-14 14:46:48

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

如果存在params或特定操作,我想要验证对象属性的存在。这是我的表格:

<%= simple_form_for(current_user, :url => { :controller => "users", :action => "request_permissions_callback"} , :method => :get) do |f| %>
 <%= f.input :external_email %>
 <%= f.hidden_field :external, :value => true %>
 <%= f.button :submit %>    
<% end %>

在我的模型上,我不知道这种方法是否正确:

class User
  include Mongoid::Document
  field :external_email
  validates_presence_of :external_email, :if => :external
  attr_accessor :external
end

或者其他方法是如何仅在行动:external_email上验证request_permissions_callback的存在?

谢谢!

1 个答案:

答案 0 :(得分:0)

我的错误是:

class User
  include Mongoid::Document
  field :external_email
  attr_accessor :external
  attr_accessible, :external_email, :external
  validates_presence_of :external_email, :if => :external
end

还需要将虚拟属性添加到attr_accessible

谢谢!