I have an address split up into @profile.street_address
, @profile.region
, @profile.zip_code
.
I want to create
@profile.address = "#{@profile.street_address} #{@profile.region} #{@profile.zip_code}"
What is the best way to do this every time my model is created or updated?
You'll be best using the before_save
to combine all the attributes into the one you want (although IMO this is bad practice):
#app/models/profile.rb
class Profile < ActiveRecord::Base
before_save :set_address
private
def set_address
self.address = "#{street_address} #{region} #{zip_code}"
end
end
Something important to consider is the role of the DRY
(Don't Repeat Yourself) principle within Rails, which means that you should only do something once, reusing it as often as required. This is extremely pertinent in the case of your data
To this end, I would highly recommend creating a custom getter
for your address
in your model:
#app/models/profile.rb
class Profile < ActiveRecord::Base
def address
"#{street_address} #{region} #{zip_code}"
end
end
This will not save the address
data to your database, but will give you the ability to load @profile.address
in your controller & views. Why is this important? Simply, because when you call address
, it will be pulling directly from the other attributes in your db, rather than the duplicated attribute you would have had otherwise
I would personally recommend this approach, but either will achieve what you want
You could set the before_save
callback.
before_save do
self.address = "#{street_address} #{region} #{zip_code}"
end
In your address class:
before_save :set_address
def set_address
self.address = "#{profile.street_address} #{profile.region} #{profile.zip_code}"
end
This assumes profile is available in your model.
It might be better to normalize your db by just making it an instance method, like this:
def address
"#{profile.street_address} #{profile.region} #{profile.zip_code}"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.