如何向simple_form添加帮助器取决于属性类型?

时间:2013-11-28 12:48:03

标签: ruby-on-rails ruby simple-form

这是我的表格:

= simple_form_for Risk.new do |f|
  = f.input :risk_id, as: :hidden, input_html: {value: risk.id}
  - if risk.answer_type.boolean?
    = f.input :answer, as: :radio_buttons
  - elsif risk.answer_type.string?
    = f.input :answer, as: :string
  - elsif risk.answer_type.integer?
    = f.input :answer, as: :integer

如何从视图中提取if语句逻辑?

1 个答案:

答案 0 :(得分:0)

您可以在application_helper.rb中设置帮助方法。见下文:

你的表格。

= simple_form_fr Risk.new do |f|
   = f.input :risk_id, as: :hidden, input_html: {value: risk.id}
   = form_answer_type risk.answer_type, f

你的助手。

module ApplicationController

    def form_answer_type obj, f
      if obj.boolean?
        return f.input :answer, as: :radio_buttons
      elsif obj.string?
        return f.input :answer, as: :string
      elsif obj.integer?
        return f.input :answer, as: :integer
      end
    end

end

看一下ActionController :: Helpers。它们非常强大,可以真正帮助您保持代码清晰简洁:http://api.rubyonrails.org/classes/ActionController/Helpers.html