【问题标题】:has many through checkboxes?有很多通过复选框?
【发布时间】: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


【解决方案1】:

您可以使用collection_check_boxes。您的学生创建表单中的以下内容就可以了。

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

【讨论】:

  • 我得到了未定义的方法 organization_ids。知道这里发生了什么吗?我有强大的参数设置“.....”.permit(....,:organization_ids => [])
  • @newto2rails 你的students 表中有organization_ids 吗?
  • 不,我没有,谢谢!只是为了确保这是正确的: add_column :students, :organization_ids, :integer
  • 我遇到了一个新问题,表单无法保存我的组织
  • @newto2rails 你需要用代码更新你的帖子并详细解释错误。
猜你喜欢
  • 2016-04-01
  • 2011-05-11
  • 1970-01-01
  • 2020-03-10
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多