【问题标题】:Append text to <option> inner html in Formstastic in Rails在Rails的Formstastic中将文本附加到<option>内部html
【发布时间】:2013-02-05 19:43:03
【问题描述】:

我有两个表:组和系列。一个系列has_many 一组和一组belongs_to 一个系列。 我正在使用 Formstastic 自动生成包含所有系列的&lt;select&gt;,因此用户将能够选择与正在创建的组相关的系列。 而是一个系列belongs_to的表台,其中has_many系列。由于系列具有相同的名称,用户不可能确切地知道他在&lt;select&gt; 中选择了哪个系列,除非他知道特定系列属于哪个单元。为此,我希望每个 &lt;option&gt; 都具有以下格式:

&lt;option value="serie_id"&gt;serie.name – unit.name&lt;/option&gt;

到目前为止(和工作)我拥有的是:

ActiveAdmin.register Group do

  form do |f|
    f.inputs "Group" do       
        f.input :serie
        f.input :name
    end                               
  f.actions                         
  end 
end

任何其他关于如何实现我的目标的建议(具体说明与该单位相关的系列)将不胜感激。

【问题讨论】:

    标签: ruby-on-rails forms select option


    【解决方案1】:

    尝试以下方法:

    # in controller
    @custom_collection = Serie.all.map{ |s| ["#{s.name} - #{s.unit.name}", s.id]}
    
    # in view
    f.input :serie, collection: options_for_select(@custom_collection)
    

    此代码假定 Serie 始终具有关联的 Unit。如果没有,它将引发错误。如果您只想在单位名称存在时显示它,请使用以下内容:

    @custom_collection = Serie.all.map do |serie|
      composed_name = s.name
      composed_name += " - #{s.unit.name}" if s.unit.present?
      [composed_name, s.id]
    end
    

    【讨论】:

    • 非常感谢,成功了!就我而言,意甲总是有一个单位,所以第一个解决方案对我来说非常有效。
    【解决方案2】:

    也许你可以在你的 Serie 模型中添加一个方法:

    def fomatted_name
      name + unit.name # if you have an association belongs_to :unit
    end
    

    在你看来:

    ActiveAdmin.register Group do
    
      form do |f|
        f.inputs "Group" do       
          f.input :serie, :label_method => :formatted_name, :as => :select
          f.input :name
        end                               
        f.actions                         
      end 
    end
    

    【讨论】:

    • 这不起作用,但实际上是一个很好的提示。当显示结果时,我需要在 Group 模型中创建一个方法,但有点不同:def unit serie.unit end
    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2023-03-13
    • 2020-12-07
    相关资源
    最近更新 更多