我在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'**
我确信它一定是简单的我忽略但似乎无法找到它。任何帮助将不胜感激:
答案 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 = {}, ...)
部分。