0

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?

choise
  • 24,636
  • 19
  • 75
  • 131
  • Your question is a bit vague, but can't you create the image in an `after_create` callback in your model? – Mischa Jan 06 '12 at 15:34
  • @Mischa good point, but i'm not able to access url-helper methods in my model to create my qr-image – choise Jan 06 '12 at 15:50
  • why not? http://stackoverflow.com/questions/341143/can-rails-routing-helpers-i-e-mymodel-pathmodel-be-used-in-models – Mischa Jan 06 '12 at 15:56

2 Answers2

2

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
Chris Bailey
  • 4,126
  • 24
  • 28
0

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367