在同一页面上创建表单的新记录,列出导致奇怪结果的所有记录

时间:2014-07-23 04:35:13

标签: ruby-on-rails

我希望有一个表单可以在同一页面上添加一个新部门,以便能够在同一页面上删除部门。但是,似乎通过为部门的表单准备一个部门的实例#index创建了一个额外的"空白"事情搞砸了。这就是我所拥有的:

形式&部门清单:

= form_for @department do |f|
  - if @department.errors.any?
    #error_explanation
      %h2
        = pluralize(@department.errors.count, 'error')
        prohibited this department from being saved:
      %ul
        - @department.errors.full_messages.each do |msg|
          %li= msg
  .form-group
    %label Department Name
    = f.text_field :name, :class => 'form-control', required: true
  .form-group
    = f.submit 'Add', :class => "btn btn-primary #{'disabled' if current_user.demo_mode}"

- if @departments.any?
  - @departments.each do |department|
    = department.name
    %br
    = link_to "Delete", department, method: :delete

和部门控制员:

class DepartmentsController < ApplicationController
  def index
    @departments = current_user.company.departments
    @department = current_user.company.departments.new
  end

  def create
    current_user.company.departments.create(
      name: params[:department][:name]
    )
    redirect_to departments_path
  end

  def destroy
    department = current_user.company.departments.find(params[:id])
    department.destroy
    redirect_to departments_path, notice: 'Department was deleted.'
  end

但是当没有保存任何部门时,它仍会列出一个空白&#34;删除&#34;无处可去的按钮。 @ departments.any?无论在这里什么都是如此。

有不同的方法吗?

2 个答案:

答案 0 :(得分:2)

问题就在这里:

@departments = current_user.company.departments
@department = current_user.company.departments.new

第二行是在列表中添加一个新的空部门,因为它改变了部门列表的引用。另外,你应该使用build而不是new。

为避免列出额外元素,您可以在列表中使用collect或reject并过滤空(并且希望无效)元素:

current_user.company.departments.select { |dep| dep.valid? }.each do ...

或者不是将模型放在控制器中的关系中,而是在要保存时执行。像:

form_for Department.new do |f|

然后在控制器上,将其保存在右侧列表中(一旦从params构建对象)。

current_user.company.departments << @department

答案 1 :(得分:-1)

我想当你提交没有输入名字字段的表格时,空记录就会被创建。

按如下方式修改您的创建方法:
  def创造     current_user.company.departments.create(       名称:params [:department] [:name]     )如果params [:department] [:name] .present?
    redirect_to departments_path
  结束

使用条件语句可以避免创建空记录。是吗?

另外,我可以在删除操作中看到一些不需要的查询:

department = current_user.company.departments.find(params[:id])
department.destroy

可以修改为

department = Department.find_by_id(params[:id])
department.destroy

您正在根据参数ID查找部门对象,因此不需要嵌套关联模型。

这可能对你有帮助..

谢谢!