问题
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 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.
回答2:
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
来源:https://stackoverflow.com/questions/3017927/generating-the-input-id-with-an-activerecord-model