产生输入ID与ActiveRecord模型 [英] Generating the input id with an ActiveRecord model

查看:211
本文介绍了产生输入ID与ActiveRecord模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何产生输入的 ID 属性,给定一个模式?举例来说,如果我有人物模型 FIRST_NAME 属性,表单助手打印出这个文本框HTML:

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" />

我怎么能生成 person_first_name 从code其他一些地方(如在一个控制器或某些地方)?

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

推荐答案

我结束了以下中微子的建议,并期待在轨codeA点点。最后我拉出一对夫妇在 InstanceTag 类的私有方法和移动起来一点点。我猴子修补这个到的ActiveRecord :: Base的,这可能不是最好的解决办法,但它现在:

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

这篇关于产生输入ID与ActiveRecord模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆