多选不保存

时间:2015-12-23 20:25:26

标签: ruby-on-rails ruby ruby-on-rails-4

我试图将相关的参数传递给具有多选列表的模型。我需要在创建新的课程条目时通过选择一个讲师来为课程提供课程。我检查了数据库,并且没有在讲座_id栏中得到任何内容。这是我的表格:

     <%= f.select(:lecturers_id, Lecturer.all.collect {|l| [ l.name, l.id ] }, {}, { :multiple => true }) %>

我的控制器:

def subject_params
    params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturers_id => [])
end
 def create
    @subject = Subject.new(subject_params)
    @subject.save
    redirect_to "/subjects" and return
end

我的观点:

 <% @lecturers.each do |lect| %>
        <tr>
            <td class='col-md-3'><%= lect.name %></td>
            <td class='col-md-3'>
                <% lect.subjects do |subj| %>
                <%= subj.name %>
                <% end %>
            </td>
    <% end %>

2 个答案:

答案 0 :(得分:0)

假设关联是Subject has_many :lecturers,那么您可以将lecturers_id更改为lecturers_ids

def subject_params
    params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturers_ids => [])
end

形式:

<%= f.select(:lecturers_ids, ...

答案 1 :(得分:0)

如果是Subject has_many :lecturers。你的表格应该是

<%= f.select(:lecturer_ids, Lecturer.all.collect {|l| [ l.name, l.id ] }, {}, { :multiple => true }) %>

,您的subject_params应为

def subject_params
    params.require(:subject).permit(:name, :credit, :number_of_hours, :lecturer_ids => [])
end