Zak*_*off 5 ruby-on-rails nomethoderror
我在rails中设置了以下内容:
Document has_many Sections
Section belongs_to Document
Run Code Online (Sandbox Code Playgroud)
Section表单在文档/ show视图中完成...此操作的Document控制器是:
def show
@document = current_user.documents.find(params[:id])
@section = Section.new if logged_in?
end
Run Code Online (Sandbox Code Playgroud)
文件/节目中的章节表格如下:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
您可以在哪里看到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
Run Code Online (Sandbox Code Playgroud)
我得到以下错误,我无法解决.
**NoMethodError (undefined method `build' for #<Document:0x00000004e48640>):
app/controllers/sections_controller.rb:6:in `create'**
Run Code Online (Sandbox Code Playgroud)
我相信它一定是简单的我忽略但似乎无法找到它.任何帮助,将不胜感激:
Aru*_*hit 13
替换以下行: -
@section = @document.build(section_params)
Run Code Online (Sandbox Code Playgroud)
同
@section = @document.sections.build(section_params)
Run Code Online (Sandbox Code Playgroud)
您有一个在模型has_many中命名的关联.因此,按照指南,你得到了方法.阅读我给你的链接下的部分.sectionsDocumentcollection.build(attributes = {}, ...)4.3.1.14 collection.build(attributes = {}, ...)