2012-03-03 3 views
0

사용자, 카테고리, 이야기 및 댓글의 네 가지 컨트롤러가 있습니다. 내 문제는 의견입니다. @ comment.save 주석을 제출하면 false이며 문제가 어디인지 이해할 수 없습니다. 댓글 DB에 내 테이블에 콘텐츠, user_id, story_id 있습니다. StoriesController에 대한레일즈가 DB에 제출 된 결과를 저장할 수 없습니다.

def new 
    @comment = Comment.new 
    @story = Story.find(params[:story_id]) 
end 

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 

show.html.erb :

<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 %> 

comment.rb :

class Comment < ActiveRecord::Base 
    attr_accessible :content, :story_id, :user_id 
    belongs_to :story 
    belongs_to :user 

    validates :content, :presence => true 
    validates :story_id, :presence => true 
    validates :user_id, :presence => true 

    default_scope :order => 'comments.created_at DESC' 
end 

story.rb

class Story < ActiveRecord::Base 
    attr_accessible :title, :content, :category_id 
    belongs_to :user 
    belongs_to :category 
    has_many :comments 

    validates :title, :presence => true 
    validates :content, :presence => true 
    validates :user_id, :presence => true 

    default_scope :order => 'stories.created_at DESC' 
end 

여기 내 코드의 일부입니다 업데이트 저장을 사용할 때! 스토리가 비어있을 수 없다는 오류 메시지가 있습니다.

+0

모델의 코드는 무엇입니까? – Dogbert

+1

저장 사용을 고려하십시오! 적어도 현재는 더 많은 정보가있는 예외가 던져 질 것입니다. 또한 @ comment.errors를 확인하십시오 (또는보다 유용한 피드백을 위해 html에서이 오류를 인쇄하는 양식 도우미 사용) –

+0

모델로 업데이트되었습니다. 저장을 사용할 때! 스토리가 비어있을 수 없다는 오류 메시지가 있습니다. – user1107922

답변

1

당신이 만든 이야기에 대한 이야기를 설정해야합니다 (분명히 다뤘으므로) 문제의 이야기는 params[:story_id]입니다. 그 이야기 ID는 마술처럼 params[:comment] 해시에 들어가는 길을 찾지 않습니다. 당신은

@comment = @story.comments.build(params[:comment]) 
@comment.user = current_user 

을하거나 사용자의 의견을 만든 다음 그 이야기를 설정할 수 있습니다 중 하나.

+0

감사합니다. 작동합니다! :) – user1107922

관련 문제