你可以在Postgres数组中使用attr_writer吗?

huangapple go评论54阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月26日 03:29:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定