views:

27

answers:

2

How do you generate an input's id attribute, given a model? For example, if I have a model of Person with a first_name attribute, the form helper prints out a textbox with this html:

<input type="text" id="person_first_name" />

How can I generate that person_first_name from some other place in the code (like in a controller or some place)?

+1  A: 

A good habit is to dig rails' code every now and then :)

These values are generated by private methods inside the nodoc-ed InstanceTag class. You can see the sources here. Methods of interest are add_default_name_and_id, tag_id, and probably tag_id_with_index. Nothing fancy there.

neutrino
Yeah, I did poke around InstanceTag for a while, but I'm still too new to ruby and rails to really grasp what's going in there yet :). I think I kept mistaking the methods without parens as attributes/properties.
swilliams
+1  A: 

I ended up following neutrino's advice and looked at the rails code a little bit more. I ended up pulling out a couple of private methods in the InstanceTag class and moving them around a little bit. I monkey patched this onto ActiveRecord::Base, which may not be the best solution, but it works right now:

def create_tag_id(method_name)
  object_name = ActionController::RecordIdentifier.singular_class_name(self)
  "#{sanitized_object_name(object_name)}_#{sanitized_method_name(method_name.to_s)}"
end

private
  def sanitized_object_name(object_name)
    object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
  end

  def sanitized_method_name(method_name)
    method_name.sub(/\?$/,"")
  end
swilliams