2011-09-25 4 views
0

나는 Ruby on Rails를 배우려고 애쓰는 초보자입니다. 나는 has_many 연관을 사용하는 법을 배우려고 노력하고있다. 나는 코멘트를 추가 할 수있는 블로그를 가지고있다. 나는 포스트 페이지에 덧글 폼을 추가 할 수 있지만 "덧글 폼 추가"를 사용하여 새 페이지로 이동하여 덧글을 추가하는 방법을 배우고 싶습니다.Rails에서 다중 모델, 다중 페이지 양식을 만드는 방법은 무엇입니까?

그러나 의견 게시에 대한 필요한 정보를 전달할 수 없습니다. 내 양식이나 comments_controller에 문제가 있는지 확실하지 않습니다.

posts_controller

class PostsController < ApplicationController 
    def show 
    @post = Post.find(params[:id]) 
    end 
    def new 
    @post = Post.new 
    end 
    def index 
    @posts = Post.all 
    end 
end 

comments_controller

class CommentsController < ApplicationController 
    def new 
    @comment = Comment.new 
    end 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create(params[:comment]) 
    redirect_to post_path(@post) 
    end 
end 

코멘트 모델

class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

후 모델

class Post < ActiveRecord::Base 
    validates :name, :presence => true 
    validates :title, :presence => true, 
        :length => { :minimum => 5 } 
    has_many :comments, :dependent => :destroy 
    accepts_nested_attributes_for :comments 
end 

코멘트 양식

<h1>Add a new comment</h1> 
    <%= form_for @comment do |f| %> 
     <div class="field"> 
     <%= f.label :commenter %><br /> 
     <%= f.text_field :commenter %> 
     </div> 
     <div class="field"> 
     <%= f.label :body %><br /> 
     <%= f.text_area :body %> 
     </div> 
     <div class="actions"> 
     <%= f.submit %> 
     </div> 
    <% end %> 

routes.rb

Blog::Application.routes.draw do 
    resources :posts do 
    resources :comments 
    end 
    resources :comments 
    root :to => "home#index" 
end 

답변

0

나는 당신의 의견 페이지 내 게시물 ID를 가질 필요가 같아요.

같은 것을 할 : 당신이 의견을 컨트롤러로 리디렉션하는 경우

, 포스트 ID를 전달하고

class CommentsController < ApplicationController 
    def new 
    @post_id = params[:id] 
    @comment = Comment.new 
    end 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create(params[:comment]) 
    redirect_to post_path(@post) 
    end 
end 

그리고 귀하의 의견/new.erb보기에서 의견 컨트롤러에서 그것을 얻을, 추가 게시물 ID를 숨겨진 매개 변수로 사용

<h1>Add a new comment</h1> 
<%= form_for @comment do |f| %> 
    <div class="field"> 
    <%= f.label :commenter %><br /> 
    <%= f.text_field :commenter %> 
    </div> 
    <div class="field"> 
    <%= f.label :body %><br /> 
    <%= f.text_area :body %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %><%= f.text_field :post_id, @post_id %> 
    </div> 
<% end %> 
+0

응답을 보내 주셔서 감사합니다. 내가 의견 컨트롤러에 post_id를 전달해야하지만 여전히 적절한 post_id로 의견을 저장할 수 없다는 것을 이해합니다. 보기에 숨겨진 매개 변수가이를 파기하는 것 같습니다. 다시 한번 감사드립니다. –

+0

안녕하세요 @monz, 솔루션을 시연하는 매우 간단한 블로그 앱을 만들었습니다. 메일이 있으면 전자 메일로 보낼 수 있습니다. – sameera207

관련 문제