2014-11-01 4 views
2

I가 레일에 설정된 다음 가지고 ...이 동작에 대한 문헌 제어기불확정 방법 빌드 4 has_many 연관

Document has_many Sections 
Section belongs_to 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 %> 

당신이 hidde를 볼 수있는 곳

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 

내가 해결하지 못하고 다음과 같은 오류가 발생합니다 : n_field_tag ​​다음과 같이

sections_controller 인가 document_ID을 보내고있다.

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

내가 간과하고있는 것이 분명하지만 쉽게 찾을 수없는 것이 틀림 없습니다. 어떤 도움을 주시면 감사하겠습니다 :

답변

7

은 아래 라인을 교체 : -

@section = @document.build(section_params) 

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

와 함께 당신은 Document 모델 sections라는 has_many 연관을 가지고있다. 따라서 guide에 따라 collection.build(attributes = {}, ...) 메서드가 있습니다. 내가 준 링크 아래에있는 4.3.1.14 collection.build(attributes = {}, ...) 섹션을 읽으십시오.

+0

답장을 보내 주셔서 감사합니다. 매우 감사합니다. – Zakoff

+0

10 분 이상 기다려야 내 수준의 업보/점수로 답변을 수락 할 수 있습니다. 대답을 수락하기 위해 돌아갑니다 :) – Zakoff

+0

@Zakoff RoR에서 아르바이트를 찾고 있는데, 제공 할 것이 있습니까? –