我有以下用于表单中选择框的代码:
<div class="field">
<%= f.label :user_id %>
<%= f.collection_select :user_id, User.all, :id, :name, include_blank: true %>
</div>
它显示以下选择选项:
I noticed that when the blank
option is selected, what actually gets saved in the database is an empty string: ''
我不想在选择 blank
选项时保存空字符串。相反:我想保存 null
。
我试图覆盖 rails 模型中的 setter,但没有成功:
def text_value=(value)
write_attribute(:name, nil) and return if value.empty?
super
end
我如何在应用程序级别执行此操作?我知道我可以在数据库级别指定默认值,但似乎这可能更适合应用程序级别。
最佳答案
这个有效:
def text_value=(value)
if value.empty?
write_attribute(:name, nil)
else
super
end
end
关于ruby-on-rails - Rails collection_select : save null instead of empty string when 'blank' option selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387221/