有很多通过复选框?

时间:2015-06-30 15:18:55

标签: ruby-on-rails checkbox many-to-many has-many-through

我与学生和组织有很多关系。在创建新学生时,我希望有一个复选框来选择一个或多个组织并保存。我该怎么做呢? MVC具体是什么样的?我无法找到任何可以全面了解的在线资源。

更新了代码:

以我的形式部分:

<%= simple_form_for (@student) do |f| %>

<div class="field">
    <%= f.label :organization_ids %><br />
    <%= collection_check_boxes :student, :organization_ids,       Organization.all, :id, :name %>
</div>
<div class="actions">
<button class="btn btn-primary" type="submit">Save</button> <%= link_to   "Cancel", :back, {:class=>"btn btn-primary"} %>
  </div>
 <% end %>

控制器:

def update
  @student = Student.find(params[:id])
  if Student.save_existing(params[:id], params[:student])
    flash[:notice] = "Student was successfully updated!"
    redirect_to students_path
  else
    flash[:error] = "Student failed to update."
    redirect_to students_path
  end
end

def student_params
   params.require(:student).permit(:name, :organization_ids => [])
end

学生表:

create_table "students", force: :cascade do |t|
   t.string   "name"
   t.datetime "created_at",  null: false
   t.datetime "updated_at",  null: false
   t.integer  "organization_id"
   t.integer  "organization_ids"
end

我的问题:当我@student.organization_ids.inspect时,它会给我一个空数组,这意味着表单没有保存我的输入表格复选框

1 个答案:

答案 0 :(得分:1)

您可以使用collection_check_boxes。您的 学生创建表单 中的内容如下所示。

<div class="field">
    <%= f.label :organization_ids %><br />
    <%= collection_check_boxes(:student, :organization_ids, Organization.all, :id, :name) %>
</div>