我有一个学生模型和一个团体模型。添加新瞳孔时,我有一个collection_select框,其中包含:multiple =>是的,这样学生就可以分成几组。
<div class="field">
<%= f.label "All Groups" %><br />
<%= collection_select(:groups, :id, @all_groups,
:id, :name, {},
{:multiple => true}) %>
</div>
我有一个编辑学生表格,当加载时选择学生之前分配的组,以便在需要时可以更改它们,因此在集合选择选项中有{}的额外位;
<div class="field">
<%= f.label "All Groups" %><br />
<%= collection_select(:groups, :id, @all_groups,
:id, :name, {selected: @previous_selection},
{:multiple => true}) %>
</div>
@previous_selection在pupils_controller中设置;
@previous_selection = Array.new
@pupil.groups.each do |pg|
@previous_selection.push(pg.id)
end
这是在def编辑块中,因此仅设置编辑页面。
这是PupilsController;
class PupilsController < ApplicationController
before_action :set_pupil, only: [:show, :edit, :update, :destroy]
def index
@pupils = Pupil.all
end
def show
@pupil_groups = @pupil.groups
end
def new
@pupil = Pupil.new
@all_groups = set_pupil_list
end
def edit
@all_groups = set_pupil_list
@previous_selection = Array.new
@pupil.groups.each do |pg|
@previous_selection.push(pg.id)
end
end
def create
@pupil = Pupil.new(pupil_params)
clean_select_multiple_params
logger.debug "The groups parameter contains: #{params[:groups][:id]}"
selected_groups = Group.find(params[:groups][:id])
@pupil.groups = selected_groups
respond_to do |format|
if @pupil.save
format.html { redirect_to @pupil, notice: 'Pupil was successfully created.' }
format.json { render action: 'show', status: :created, location: @pupil }
else
format.html { render action: 'new' }
format.json { render json: @pupil.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @pupil.update(pupil_params)
clean_select_multiple_params
selected_groups = Group.find(params[:groups][:id])
@pupil.groups = selected_groups
format.html { redirect_to @pupil, notice: 'Pupil was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @pupil.errors, status: :unprocessable_entity }
end
end
end
def destroy
@pupil.destroy
respond_to do |format|
format.html { redirect_to pupils_url }
format.json { head :no_content }
end
end
def full_name
@fn = @pupil.given_name
@sn = @pupil.surname
@full_name = @fn + @sn
end
private
def set_pupil
@pupil = Pupil.find(params[:id])
end
def set_pupil_list
Group.all
end
def clean_select_multiple_params hash = params
hash.each do |k, v|
case v
when Array then v.reject!(&:blank?)
when Hash then clean_select_multiple_params(v)
end
end
end
def pupil_params
params.require(:pupil).permit(:given_name, :surname, :date_of_birth, :gender, :ethnicity)
end
end
当请求新的pupil页面时,使用_form.html.erb文件,其中包含{selected:@previous_selection}参数,该参数尚未由pupils_controller中的def new设置,但没有错误消息关于@previous_selection没有被初始化。
我希望有一个错误,但我没有得到一个,但不明白为什么。有人可以解释一下吗?我是编程的新手,如果我使用了错误的术语,我很抱歉。
谢谢
莱昂
答案 0 :(得分:1)
@previous_selection
变量为nil
,因此在视图中,不会选择collection
个项目。没有必要将variable
初始化为nil
, rails 会这样做。