【问题标题】:Undefined method build in rails 4 has_many association在 rails 4 has_many 关联中构建未定义的方法
【发布时间】:2014-11-01 20:25:49
【问题描述】:

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

Document has_many Sections
Section belongs_to Document

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

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

documents/show中的Section形式如下:

<%= 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'**

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

【问题讨论】:

    标签: ruby-on-rails nomethoderror


    【解决方案1】:

    替换下面的行:-

    @section = @document.build(section_params)
    

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

    您在 Document 模型中有一个名为 sectionshas_many 关联。因此,根据guide,您得到了方法collection.build(attributes = {}, ...)。阅读我给你的链接下的4.3.1.14 collection.build(attributes = {}, ...)部分。

    【讨论】:

    • 感谢您的快速回复,非常感谢,它成功了:)
    • 我必须等待 10 多分钟才能以我的业力/积分水平接受您的回答。我会回来接受答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2015-04-17
    • 1970-01-01
    相关资源
    最近更新 更多