2016-12-07 51 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

非常感謝,您已經很容易理解。 –