나는 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
응답을 보내 주셔서 감사합니다. 내가 의견 컨트롤러에 post_id를 전달해야하지만 여전히 적절한 post_id로 의견을 저장할 수 없다는 것을 이해합니다. 보기에 숨겨진 매개 변수가이를 파기하는 것 같습니다. 다시 한번 감사드립니다. –
안녕하세요 @monz, 솔루션을 시연하는 매우 간단한 블로그 앱을 만들었습니다. 메일이 있으면 전자 메일로 보낼 수 있습니다. – sameera207