2017-02-23 109 views
0

好吧,我使用的是Rails 5和最新的Ruby稳定版本。我试图做的是有一个选择框在编辑视图上选择正确的选项。Ruby On Rails - 表单选择下拉选择编辑上的选项

这是我迄今为止 create_users

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 

有这些表之间没有关系,所有的用户类型仅仅是一个支持表。 我可以得到它输出下拉并保存到数据库我只是不能得到补救的事情来显示在编辑适当的选择选项。

这里是我的表单代码

<%= 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 %> 

回答

1

使用在options_for_select价值,它有一个可选的参数selected

options_for_select(user_type_array, f.object.user_type_id) 
+0

完美谢谢!像魅力一样工作,forms_for有时会有点混乱!再次感谢! –