Gem form_for 的 collection_select 这种结构有没有 API 可以直接生成。

bydmm · 2013年04月17日 · 最后由 leomayleomay 回复于 2013年04月17日 · 2669 次阅读

我们正在写一个 GEM,把http://aehlke.github.io/tag-it/ 封装好,变成 form_for 的一个插件。 我们想要的代码结构是

<%= form_for @video do |f| %>
<%= f.tagit :tag %>
<% end %>

这个 GEM 的目的是,把下面的 collection_select 转化为 tagit 的形式。

<%= form_for @video do |f| %>
<%= f.collection_select :tag %>
<% end %>

我们参考了 rails_kindeditor 的代码。https://github.com/Macrow/rails_kindeditor

他的使用形式和我们想要的类似

<%= form_for @video do |f| %>
<%= f.kindeditor :content %>
<% end %>

rails_kindeditor 的核心实现代码。

def kindeditor(name, method, options = {})
  input_html = (options.delete(:input_html) || {})
  hash = input_html.stringify_keys
  instance_tag = ActionView::Base::InstanceTag.new(name, method, self, options.delete(:object))
  instance_tag.send(:add_default_name_and_id, hash)      
  output_buffer = ActiveSupport::SafeBuffer.new
  output_buffer << instance_tag.to_text_area_tag(input_html)
  output_buffer << javascript_tag(js_replace(hash['id'], options))
end

他用到了 ActionView::Base::InstanceTag 这个类。 然后这个类实现了 to_check_box_tag,to_label_tag 等方法。 但是没有 to_collection_select 这个方法。 而我们自己实现和拼接一个多对多的 select 的 html 代码又过于丑陋。 请问有没有任何 RAILS 的 API,有没有生成 collection_select 的方法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号