在rails中保存/更新时,如果在before_save回调中满足条件,是否可以跳过/忽略列?
例如,我有一个 Products 表,它有两列:
和 ProductTranslations 表
是否可以像这样使用before_save回调:
class Products < ActiveRecord::Base
has_many :translations
before_save :check_locale
private
def check_locale
if I18n.locale != :en
# save/update only the price column and don't update name column
# find ProductTranslation record of product name and update it
else
# save/update both the price price column and product name
end
end
end
忽略更新名称列的代码是什么?
另外,我并不打算像postgres那样使用像hstore_translations这样的gem,因为我希望尽可能将代码作为模型的一部分创建,以后可能会在以后参考。谢谢。
答案 0 :(得分:1)
class Products < ActiveRecord::Base
has_many :translations
before_update :check_locale
private
def check_locale
if I18n.locale != :en
translations.find_by_local(I18n.locale).update name_translation: name
write_attribute :name, name_was
#by owerriding wirte attribute name with name_was(rails cool
#thing to get property value that was there before
#the new one the one you are sending)
else
# save/update both the price price column and product name
end
end
end