我是RubyOnRails的新手 我想创建用户将其分配给组,但问题是用户不知道group_id, 用户只知道他/她的课程和教职员工。我需要按课程和教师找到group_id
Group has_many :users
User belongs_to :group
I added migration AddGroupIdToUsers group_id:integer
new.html.erb
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :surname %>
<%= f.text_field :surname %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
<label for="person_group_id">Group:</label>
<%= collection_select(:group,:id,Group.all,:id,:course, :prompt => "Select a Group")%>
<label for="person_faculty_id">Faculty:</label>
<%= collection_select(:group,:faculty,Group.all,:id,:faculty, :prompt => "Select a Faculty")%>
<%= f.label :id, "Group_ID" %>
<%= f.text_field :group_id %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
非常感谢你!
答案 0 :(得分:0)
实现这一目标的最佳方法是使用simple_form
您所要做的就是:
<%= f.association :group %>
它会自动为Group.all
创建一个下拉列表您可以通过以下方式传递:radio,as :: collection,最适合您的需求。
请参阅:https://github.com/plataformatec/simple_form
你的表格也会更清晰。
看起来如下(未经测试):
<%= simple_form_for (@user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.input :name %>
<%= f.input :surname %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
<%= f.association :group%>
<%= f.button :submit, class: "btn btn-large btn-primary" %>
<% end %>
答案 1 :(得分:0)
而不是这一行
<%= collection_select(:group,:id,Group.all,:id,:course, :prompt => "Select a Group")%>
试试这个
<%= collection_select(:user,:group_id,Group.all,:id,:course) %>
collection_select
的语法是object,method,collection,value_method,text_method,options,html_options
这是陈述
<select name="object[method]">
<option value="value_method">text_method</option>
<option value="value_method">text_method</option>
<option value="value_method">text_method</option>
....
</select>
或在你的情况下
<select name="user[group_id]">
<option value="1">Course 1</option>
<option value="2">Course 2</option>
<option value="3">Course 3</option>
....
</select>
显然也可以在适当的庄园中编辑这一行
<%= collection_select(:group,:faculty,Group.all,:id,:faculty, :prompt => "Select a Faculty")%>