gpt4 book ai didi

ruby-on-rails - 在 rails 4 has_many 关联中构建未定义的方法

转载 作者:行者123 更新时间:2023-12-04 16:52:39 27 4
gpt4 key购买 nike

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

Document has_many Sections
Section belongs_to Document

Section 表单在文档/显示 View 中完成...此操作的文档 Controller 是:
  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'**

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

最佳答案

替换以下行:-

@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 = {}, ...)在我给你的链接下。

关于ruby-on-rails - 在 rails 4 has_many 关联中构建未定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com