2012-03-02 3 views
0

사용자, 카테고리, 이야기 및 댓글과 같은 컨트롤러가 있습니다. 내가 의견을 말할 때까지는 모든 것이 괜찮았다. 내 DB에서 content, user_id, story_id를 저장하려고하지만 테이블이 비어 있습니다. @ comment.save는 false입니다. 여기에 내 코드의 일부는 다음과 같습니다레일이 DB에 결과를 저장할 수 없습니다.

CommentsController : StoriesController에 대한

def create 
    @story = Story.find(params[:story_id]) 
    @comment = @story.comments.create(params[:comment]) 
    if @comment.save 
    flash[:success] = "Successfull added comment" 
    redirect_to stories_path 
    else 
    render 'new' 
    end 
end 

show.html.erb : StoriesController에서 나는이 같은 일을했지만 지금은 이해할 수없는

<b><%= @story.title %></b> <br/><br/> 

<%= @story.content %> <br/><br/> 

<% @story.comments.each do |comment| %> 
    <b>Comment:</b> 
    <%= comment.content %> 
<% end %> 

<%= form_for([@story, @story.comments.build]) do |f| %> 
    <div class="field"> 
    <%= f.label :content %><br /> 
    <%= f.text_area :content %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Add" %> 
    </div> 
<% end %> 

방법 해.

def create 
    @categories = Category.all 
    @story = current_user.stories.build(params[:story]) 
end 
+0

거짓이다? 이야기와 댓글 사이에 조인을 설정 했습니까? – ellawren

+0

어떻게해야할지 모르겠지만 서버를 다시 시작하면 오류 메시지의 문제가 해결되었지만 Comments 테이블은 DB가 비어 있습니다. 그리고 나는 story.rb has_many : comment와 comment.rb - belongs_to : story에있다. route.rb에서 내가 가진 : 자원 : 이야기 자원을 수행 최종 – user1107922

+0

가 지금은 다시 오류 메시지가 코멘트 ..를이 라인에서 : @comment = current_user.comments.create (PARAMS는 [: 코멘트]) – user1107922

답변

1

오류 : "무기 호에 대한 정의되지 않은 방법 NilClass은"나는하지 않은 경우 모델/클래스가 인스턴스화지고있는 경우에있을 때 항상 저를 물린 것으로 보인다. 당신은 줄에이 오류가 발생하는 경우 :

@comment = current_user.comments.create(params[:comment]) 

난 당신의 코드는 로그인 한 사용자, 그래서 CURRENT_USER는 전무없이 실행되고 있다고 생각합니다. 당신의 @comment 코드의 구조는 등록 된 사용자가 주석을 만들 수 있도록하기 위하여려고하고 있음을 나타냅니다, 그래서 당신은이 방법을 시도 할 수 있습니다 :이 도움이

if current_user 
    @comment = current_user.comments.create(params[:comment]) 
else 
    redirect :root, :notice => "Sorry you must be registered and logged in to comment" 
end 

희망을.

+0

가 변경 그것은 당신이 쓴 방법이지만 내가 로그인 할 때 문제가 여전히 여기에 있습니다. 그리고 오류 메시지는이 줄에 있습니다. – user1107922

0

나는 매우 어리 석다! 나는 사용자 모델에서 has_many 주석을 놓쳤다. 그러나 주석의 내용이 DB에 저장 될 수없고 테이블 주석이 비어 있기 때문에 이제는 문제가 여전히 여기에있다. comment.save @

내 경우 특별히 오류의 원인이되는 라인

def create 
    @story = Story.find(params[:story_id]) 
    if current_user 
    @comment = current_user.comments.create(params[:comment]) 
    end 

    if @comment.save 
    flash[:success] = "Successfull added comment" 
    redirect_to story_path(@story) 
    else 
    render 'new' 
    end 
end 
+0

시도 할 사항 : 1) 주석에 user_id 열과 belongs_to 문을 추가했는지 확인하십시오. 2) 논리 문제 : 첫 번째 if 문이 실패하면 @comment 변수가 만들어지지 않고 두 번째 if 문이 조건을 생성합니다 . 3) 모든 주석 필드가 attr_accessible인지 확인하십시오. - dev 로그를 점검하여 경고를 받고 있는지 확인하십시오. 4) 코드에서 수동으로 테스트 주석을 작성하고 저장하십시오. (create ... (params [: comment]) 5) 서버 콘솔 params [: comment]에 puts() 다시 보냅니다. –

관련 문제