如何在Rails中创建多模型,多页面的表单?
问题描述:
我是一个试图学习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
答
我想你需要有内部的您的评论页面的帖子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 %>
感谢您的回复,但我仍然卡住了。我知道我需要将post_id传递给评论控制器,但我仍然无法通过正确的post_id保存评论。视图中隐藏的参数似乎打破了它。再次感谢。 –
嗨@monz,我创建了一个非常简单的博客应用程序来演示您的解决方案,如果我有邮件,我可以通过电子邮件发送邮件 – sameera207