0

试图将嵌套资源(名为“文件夹”)索引嵌入到父(名为“用户”)“显示”查看器,我发现了一个问题。在进行数据库创建/迁移之后(当尚未对“文件夹”表进行任何显式操作时),我创建了用户条目。创建后,该用户的“显示”方法向我显示了一个包含 NilClass 字段的文件夹。一个条目,无论显示哪个用户,它总是默认包含这个 Nil-ed 条目。我可以添加其他条目,但始终会显示此条目。

还有一件有趣的事情:在rails 控制台中@user.folders 返回空数组,并且它的#each 方法运行良好(即在控制台中所有的东西都正常运行,这个问题不会出现在那里)。

这是嵌套资源的“创建”方法:

class FoldersController < ApplicationController
  def create
    @user = User.find params[:user_id]
    @user.folders.create params[:folder]
    redirect_to user_path @user
  end

users/show.html.haml - 父查看器(用户信息输出被切断以使代码更易于阅读):

Add a folder:
=form_for [ @user, @user.folders.build] do |f|
  .field
    =f.label :name
    =f.text_field :name
  .actions
    =f.submit

%br
User's folders:
%table
  %tr
    %th Name
    %th
    %th
  -@user.folders.each do |folder| # Will make at least one iteration even if 
                                  # no entries have been created yet. Works  
                                  # properly in rails console
      %tr
        %td= folder.name.class ## here will be NilClass in that default entry
        %td= link_to 'Show', user_folders_path(@user, folder)
        %td= link_to 'Delete', [@user, folder], :confirm => 'Are you sure?', :method => :delete

我是 Rails 和基于 Web 的应用程序的新手,因此,如果某些内容描述不正确,请随时提出问题,并批评编码错误。

更新: UserController::create 方法:

def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end
4

1 回答 1

1

我刚刚遇到了类似的问题。在您使用的 form_for 标记中

@user.folders.build

这是使用适当的 user_id 属性向您的文件夹对象添加一个空文件夹记录。

在您的代码中,您正在遍历相同的文件夹对象,这就是您看到空记录的原因。

如果您只是将表单代码放在文件夹代码表下方,您会看到空记录不再存在(因为它尚未创建!)

于 2014-04-21T23:55:21.540 回答