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

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

Can I use an attr_writer with a Postgres Array?

问题

  1. 我有一个复选框的集合,它将响应的数组保存到数据库中的一个Postgres数组列中。问题是未选中的选项传递为空字符串,因此最终得到的结果是:

['a', '', 'c']

  1. 如果我尝试设置一个attr_writer在保存时清理数组:
  2. ```ruby
  3. def multiple_response=(val)
  4. val.compact_blank
  5. end

甚至只是:

  1. attr_writer :multiple_response

然后什么都不会保存到数据库。我做错了什么?

  1. <details>
  2. <summary>英文:</summary>
  3. 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']

  1. If I try to setup an attr_writer to clean the array on save:

def multiple_response=(val)
val.compact_blank
end

  1. or even just

attr_writer :multiple_response

  1. Then nothing is saved to the database. What am I doing wrong?
  2. </details>
  3. # 答案1
  4. **得分**: 0
  5. 这是您需要的,删除空白后,您应该调用super,这是用于保存属性的ActiveRecord方法:
  6. ```ruby
  7. def multiple_response=(val)
  8. super(val.compact_blank)
  9. end
英文:

This is what you need, after removing blanks, you should call super, ActiveRecord's method for saving the attribute:

  1. def multiple_response=(val)
  2. super(val.compact_blank)
  3. 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:

确定