Reputation: 25244
so i need to create an image that belongs to my model (string with the url of the image) in the models create method. the problem is, that this image is a QR-Code that should contain the url of the object that gets created.
but the URL (of course) is unknown in the create method because no id exists at that point for the given object.
any ideas how to solve this problem?
Upvotes: 0
Views: 116
Reputation: 4136
I don't see an obvious way of doing this, beyond using a non id column within the URL (e.g. make a call to generate a UDID/GUID, and use that in the url http://mysite.com/obj/#{udid}), or saving in two stages, using the after_create callback to set the image once the record has been saved:
class MyModel < ActiveRecord::Base
after_create :set_image
def set_image
if image_attribute == nil
image_attribute = generate_a_qr_code(self)
self.save
end
end
end
Upvotes: 2
Reputation: 230286
Use two-pass saving :-)
def create
model = Model.new params[:model]
if model.save
# at this point you have an id
model.qr = generate_qr model
model.save
# proceed as usual
end
end
This is for traditional databases with auto-increment column as primary key. In some databases, keys are generated using sequences that you can query to get a new value (before saving your object). In some databases (MongoDB) keys can be generated on the client completely.
Upvotes: 0