How to use Rails model setter methods?
ekampp opened this issue · 1 comments
ekampp commented
How do I override AR setters?
I have a model, Page, which has a translated title:
class Page < ApplicationModel
translates :title
end
This works fine, but I would like to also sanitize the input, when I directly assign the title attribute. E.g.
page = Page.find(1)
page.title = "<H1>Hello</H1>" # => Should strip tags
So I implement a setter:
class Page < ApplicationRecord
translates :title
def title=(string)
super string.sanitize # sanitize is my own method on the string class
end
end
I would expect the above code to work, but it doesn't get translated. So what's the intended pattern here?
Gems:
gem 'activerecord', '7.0.0'
gem 'globalize', '6.0.1'
stale commented
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.