【问题标题】:Prepending Default Value in Rails Select Form Helper在 Rails Select Form Helper 中添加默认值
【发布时间】:2016-02-02 01:17:17
【问题描述】:

我在尝试将默认值添加到我的表单助手选择下拉列表时遇到了错误。我做错了什么?

<%= f.select :type_page_id, @type_pages.collect {|t| [t.name,t.id],["Pagina Principal",0]},} %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    我现在明白你的意思了。毫无疑问,你有很多方法可以完成这种事情。我最喜欢的方式是在控制器中执行此操作:

    @type_pages = TypePage.all.collect do |type_page|
       [type_page.name, type_page.id]
    end.unshift(['Pagina Principal', 0])
    

    然后,当您在 html.erb 的表单助手中时,您可以使用:

    <%= f.select :type_page_id, @type_pages %>
    

    【讨论】:

    • 我需要添加一个不在我的数据库中的值,但我得到错误 sintaxys: {|t| [t.name,t.id],["Pagina Principal",0]}
    【解决方案2】:

    假设您尝试将 Pagina Principal 设为 @type_pages 名称中的默认选择

    <%= f.select :type_page_id, @type_pages.map(&:name), selected: "Pagina Principal" %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 2018-09-17
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2013-09-21
      相关资源
      最近更新 更多