如何使用RoR助手添加组合框?

Tat*_*tat 6 database ruby-on-rails

我有一个这样的:

<% form_for(@user) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </p>
  <p>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>             
 <p>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </p>
    <p>
        <%= f.label :role %> <br/>
        <%= f.text_field :role%>
    </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>            
Run Code Online (Sandbox Code Playgroud)

在数据库中,role是一个"Char"字段.我希望它与文本字段不同,用户可以选择"教师","学生",如果用户选择"教师",数据库将存储"T",否则,它将存储"S".我怎么能这样做?我有必要在数据库中添加"用户角色"表,然后与用户建立关系吗?但有必要这样做吗?感谢你.

Sal*_*lil 18

参考选择options_for_select

<%= f.select :role, options_for_select([["Teacher", "t"], ["Student", "s"]]) %>
Run Code Online (Sandbox Code Playgroud)

  • 我想你可能意味着`f.select`而不是`f.select_tag`,对吗? - 因为你有表单生成器实例`f`. (2认同)