我不认为update_attribute 会有用,因为它将用新值替换数组而不是附加到它(但请参阅下面的 --Update-- 部分更好的解释)。
我不确定这里有哪些最佳做法,但如果还没有的话,这应该可以添加一些东西:
question.tags << :ruby unless question.tags.include?(:ruby)
question.save
我会在 Question 模型上编写一个自定义方法来管理添加标签和检查唯一性:
def add_tag(tag)
if tags.include?(tag)
# do whatever you want to do when tag isn't unique
p "#{tag} is already in tags!"
else
tags << tag
save
end
end
然后用question.add_tag(:ruby)调用它。
-------- 更新-----------
如果这不起作用,可能是 ActiveRecord 无法识别字段已更改的问题(尽管它在 Rails 4.2 中似乎可以正常工作)。
这些链接解释了这个问题:
New data not persisting to Rails array column on Postgres
http://paweljaniak.co.za/2013/07/28/rails-4-and-postgres-arrays/
正如他们解释的那样,您可以在此处使用update_attribute,但您需要替换整个数组而不是将值压入其中,如下所示:
question.update_attribute(:tags, question.tags << tag)
您还应该能够强制 ActiveRecord 考虑通过包含 will_change! 来更新属性,如下所示:
def add_tag(tag)
if tags.include?(tag)
# do whatever you want to do when tag isn't unique
p "#{tag} is already in tags!"
else
tags_will_change!
tags << tag
save
end
end