根据我的理解,保存到数据库的空表单字段通常默认为nil(这是我想要的)。但是我的两个可选表单字段保存为空(“”)而不是nil。
我不确定为什么会这样,我看过:Understanding Rails validation: what does allow_blank do?和Save blank value as nil in database认为可能是因为我正在使用allow_blank: true
。
我的group.rb
# meetup_urlname must be unique
validates :meetup_urlname, uniqueness: { case_sensitive: false, message: "this is already being used by a different group" }, allow_blank: true
# only validate if meetup_apikey or if meetup_urlname is non-empty
validate :url_name_valid?, :if => :meetup_urlname?
validate :api_key_valid?, :if => :meetup_apikey?
_Form.html.erb:
<%= bootstrap_form_for(@group, :html => { :multipart => true }, layout: :horizontal, label_col: "col-sm-3", control_col: "col-sm-9") do |f| %>
...
<h5>Import Events from Meetup</h5>
<div class="field">
<%= f.text_field :meetup_urlname, label: "Meetup Group's URL", type: "text", placeholder: "Enter your Meetup group's url to retrieve your events", prepend: 'http://www.meetup.com/' %>
</div>
<div class="field">
<%= f.text_field :meetup_apikey, label: 'Meetup API Key', placeholder: 'Enter your Meetup API key (Required for advanced meetup functionality)' %>
</div>
<%= f.hidden_field :status %>
<%= f.hidden_field :audit_status %>
<%= f.hidden_field :sref %>
<div class="col-sm-10" style="padding-right: 26px;">
<div class="actions pull-right">
<%= f.submit 'Update Group', class: "action-btn btn-rounded btn-large" %>
</div>
</div>
<% end %>
有没有办法让可选的表单字段默认保存为nil而不是空?目前有一个hack在哪里如果表单字段返回空..它将覆盖为nil。
任何反馈或见解都会有所帮助。谢谢!
答案 0 :(得分:0)
strip_attributes gem可以为您处理这个问题。
答案 1 :(得分:0)
你能发布更多背景吗?
通过我们在这里得到的东西,我的想法是:
""
来自视图中的某个位置(请粘贴)to_s
上的某个地方:meetup_urlname
打电话? nil.to_s
将在ruby中返回""
。