【问题标题】:Preselect an option with rails f.select helper?使用 rails f.select 助手预选一个选项?
【发布时间】:2011-12-30 22:30:17
【问题描述】:

我有一个模型问题,其中有一个名为 category 的列。

我有一个列出所有有效类别的数组:Question.categories

<%= form_for(@question) do |f| %>
    <%= f.select :category, options_for_select(Question.categories) %>
    #...
<% end %>

假设我有一个名为@currentlySelectedCategory 的变量。

现在我如何告诉 Rails 在下拉菜单中预先选择与@currentlySelectedCategory 匹配的选项?

【问题讨论】:

    标签: ruby-on-rails html-helper


    【解决方案1】:
    <%= form_for(@question) do |f| %>
        <%= f.select :category, options_for_select(Question.categories, @currentlySelectedCategory) %>
        #...
    <% end %>
    

    但是由于您使用的是form_for,我原以为rails会选择问题类别。

    【讨论】:

    • 很高兴我能帮上忙,但您应该阅读文档以了解此类事情;)
    • 我阅读了有关选择和相关方法的文档,但没有任何帮助。我没有意识到我应该查看 options_for_select 的文档:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2011-06-19
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多