views:

28

answers:

2

Hello, I am using partials in Rails combined with jQuery child field templates to dynamically generate forms with multiple nested child attributes. Within these partials is JavaScript that is fired when various events (e.g. onChange) occur in the form, and the code that executes needs to change the DOM for a related but different form element. In this particular case, I'm using it to add multiple sale transactions in a point-of-sale type solution to a particular group of transactions and control what data is collected for each transaction. So, for example:

  1. User clicks on a link that adds 3 new transaction records to the transaction group.
  2. User sets different values in each of those three transaction records, each of which fires an onChange event that calls a JS function that needs to manipulate the DOM for each of the events in different ways. (Example: transaction 1 may be a return, so it changes the text of the transaction from cost to refund, transaction 2 may be for a service, so it changes the taxable status, etc...)
  3. The JS function has to be able to change the DOM for the correct transaction.

My problem is #3 - the DOM elements being modified are not the same as the element generating the event, so I can't use JS this. They are part of a common parent element (i.e. they share a parent <div>), so it may be possible for me to use jQuery parent/child selectors to navigate to the correct element in the DOM. However, even this requires some uniqueness in the div id attributes, and I'm not sure of the best way in Rails to dynamically generate these.

I suppose I could use random values, but this seems bad because it's not truly guaranteed to be unique and just seems like a hack. I suppose I could try to introduce some kind of counter, but this seems to violate the principles of Rails development.

Any guidance is appreciated. Thanks!

A: 

you could use Time.now as unique-id when creating a new tag

Time.now.to_i

it's not an hack or something that goes against Rails principles ;-)

apeacox
Thanks - my only concern with this is that to_i only measures time with a fidelity in seconds, so if someone clicked the link very quickly, two sets of divs could be added with the same id. I suppose I could use to_f, which would be higher fidelity... I'll see how that works.
Chris Hart
yes, you can use to_f instead of to_i to get more sharpness ;)
apeacox
A: 

Using the current time is recipe for pain and unexplained bugs. I highly recommend you use something like a GUID generator for generating unique IDs.

Redbeard