【问题标题】:Ruby On Rails - Forms For Select Dropdown Selected option on EditRuby On Rails - 用于选择下拉列表的表单编辑上的选定选项
【发布时间】:2017-02-23 05:44:18
【问题描述】:

好的,我正在使用 Rails 5 和最新的稳定版本的 Ruby。我正在尝试做的是让一个选择框在编辑视图上选择正确的选项。

这是我目前所拥有的 创建用户

class CreateUsers < ActiveRecord::Migration[5.0]
   def change
      create_table :users do |t|
         t.string :email
         t.string :password
         t.integer :user_type_id
         t.timestamps
      end
   end
end
class CreateUserTypes < ActiveRecord::Migration[5.0]
   def change
      create_table :user_types do |t|
         t.string :name
         t.text :description
         t.timestamps
      end
   end
end

这些表之间没有关系,所有的UserType都只是一个支持表。 我可以让它输出下拉列表并保存到数据库我只是无法让该死的东西在编辑时显示适当的选定选项。

这是我的表单代码

<%= form_for(user) do |f| %>
      <% if user.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

          <ul>
          <% user.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>



      <div class="field">
        <%= f.label :email %>
        <%= f.text_field :email %>
      </div>

      <div class="field">
        <%= f.label :password %>
        <%= f.text_field :password %>
      </div>

      <div class="field">
        <%= f.label :user_type_id %>

        <%#= select_tag('user_type', options_for_select(UserType.all.collect {|ut| ut.name ut.id})) %>
        <% user_type_array = UserType.all().map { |type| [type.name, type.id]} %>
        <%= f.select(:user_type_id, options_for_select(user_type_array), :selected => f.object.user_type_id) %>
        <%#= options_from_collection_for_select(UserType.all(), :id, :name) #just outputs text %>
        <%#= f.select_tag('user_type_id', options_from_collection_for_select(UserType.all(), :id, :name)) %>
      </div>
    <%= params.inspect %>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

【问题讨论】:

    标签: ruby-on-rails ruby forms form-for


    【解决方案1】:

    使用options_for_select中的值,它需要一个可选的selected参数:

    options_for_select(user_type_array, f.object.user_type_id)
    

    【讨论】:

    • 非常感谢!像魅力一样工作,forms_for 有时会有点混乱!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2011-12-23
    • 2022-01-08
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多