rails 4中的未定义方法构建has_many关联

时间:2014-11-01 20:25:50

标签: ruby-on-rails nomethoderror

我在rails中设置了以下内容:

Document has_many Sections
Section belongs_to Document

Section表单在文档/ show视图中完成...此操作的Document控制器是:

  def show
    @document = current_user.documents.find(params[:id])
    @section = Section.new if logged_in?
  end

文件/节目中的章节表格如下:

<%= form_for(@section) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
      <%= f.text_area :content, placeholder: "Compose new section..." %>
  </div>
  <%= hidden_field_tag :document_id, @document.id %> 
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

您可以在哪里看到hidden_​​field_tag正在发送document_id

sections_controller如下:

class SectionsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy, :show, :index]

  def create
    @document = Document.find(params[:document_id])
    @section = @document.build(section_params)
    if @section.save
      flash[:success] = "Section created!"
      redirect_to user_path(current_user)
    else
      render 'static_pages/home'
    end
  end

  def destroy
  end

  def index
  end

  private

    def section_params
      params.require(:section).permit(:content)
    end
end

我收到以下错误,但我无法解决。

**NoMethodError (undefined method `build' for #<Document:0x00000004e48640>):
  app/controllers/sections_controller.rb:6:in `create'**

我确信它一定是简单的我忽略但似乎无法找到它。任何帮助将不胜感激:

1 个答案:

答案 0 :(得分:12)

替换以下行: -

@section = @document.build(section_params)

@section = @document.sections.build(section_params)

has_many模型中有sections个名为Document的关联。因此,根据guide,您获得了方法collection.build(attributes = {}, ...)。请阅读我提供给您的链接下的4.3.1.14 collection.build(attributes = {}, ...)部分。