2016-12-07 84 views
1

new.html.erb的Rails:了解自定义表单辅助

<%= form_for @star do |f|%> 
    <%= star_radio(f, true)%> 
<% end %> 

stars_helper.rb

module StarHelper 
    def star_radio(form, status) 
    form.label "star_#{status}", class: 'radio-inline' do 
     form.radio_button(:star, status) + i18n_star(status) 
    end 
    end 

    def i18n_star (status) 
    I18n.t("activerecord.attributes.star.is_sun.#{status}") 
    end 
end 

我看到了一块类似的代码上面。
我不熟悉自定义表单助手。
您能否告诉我们为什么我们可以在块内使用form.radio_button(:star, status) + i18n_star(status)以及为什么我们可以使用'+'在单选按钮上添加文本。
如果你能告诉我我可以去哪里学习,我将不胜感激。

回答

1

帮助程序返回一个字符串,I18n.t也返回一个字符串。所以,你可以连接它们。

更多细节表单标签是如何产生的

这是radio_button代码:

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/form_helper.rb

def radio_button(object_name, method, tag_value, options = {}) 
    Tags::RadioButton.new(object_name, method, self, tag_value, options).render 
end 

看执行的渲染方法

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/tags/radio_button.rb#L20

def render 
    options = @options.stringify_keys 
    options["type"]  = "radio" 
    options["value"] = @tag_value 
    options["checked"] = "checked" if input_checked?(object, options) 
    add_default_name_and_id_for_value(@tag_value, options) 
    tag("input", options) 
end 

标记辅助生成HTML标记,并返回他作为HTML萨法德字符串:

https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/tag_helper.rb#L67

def tag(name, options = nil, open = false, escape = true) 
    "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe 
end 
+0

谢谢您的回答。作为一个初学者,大多数时候我用户形式助手像'<%= f.label:attr%><%= f.radio_button:attr%>',但是这里使用的块就像这样'form.label“star _#{status }“,class:'radio-inline'do form.radio_button(:star,status)+ i18n_star(status) end'。我很困惑这个 –

+0

是的,你可以将代码块传递给表单的标签方法。方法定义中的最后一个参数'&block''def label(object_name,method,content_or_options = nil,options = nil,&block)'https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers /form_helper.rb#L750 –

+0

非常感谢,您已经很容易理解。 –