【发布时间】:2015-09-17 11:37:32
【问题描述】:
我与学生和组织有着多对多的关系。创建新学生时,我希望有一个复选框来选择一个或多个组织并保存。我该怎么做呢? 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 时,它给了我一个空数组,这意味着表单没有保存我的输入表单复选框
【问题讨论】:
-
你能用模型代码更新你的帖子吗?
-
这个 Q/A stackoverflow.com/questions/7698952/… 可能会对你有所帮助
-
这是整个表单代码吗?
-
你的更新方法是怎样的?可以发一下吗?
-
没问题!刚刚发布
标签: ruby-on-rails checkbox many-to-many has-many-through