英文:
Can I use an attr_writer with a Postgres Array?
问题
我有一个复选框的集合,它将响应的数组保存到数据库中的一个Postgres数组列中。问题是未选中的选项传递为空字符串,因此最终得到的结果是:
['a', '', 'c']
如果我尝试设置一个attr_writer在保存时清理数组:
```ruby
def multiple_response=(val)
val.compact_blank
end
甚至只是:
attr_writer :multiple_response
然后什么都不会保存到数据库。我做错了什么?
<details>
<summary>英文:</summary>
I have a collection of checkboxes that save an array of responses to the database, in a Postgres array column. The problem is that unchecked options come through as empty strings, so I end up with
['a', '', 'c']
If I try to setup an attr_writer to clean the array on save:
def multiple_response=(val)
val.compact_blank
end
or even just
attr_writer :multiple_response
Then nothing is saved to the database. What am I doing wrong?
</details>
# 答案1
**得分**: 0
这是您需要的,删除空白后,您应该调用super,这是用于保存属性的ActiveRecord方法:
```ruby
def multiple_response=(val)
super(val.compact_blank)
end
英文:
This is what you need, after removing blanks, you should call super, ActiveRecord's method for saving the attribute:
def multiple_response=(val)
super(val.compact_blank)
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论