【发布时间】:2014-08-25 00:02:52
【问题描述】:
我正在寻找一种与评论一起创建评论的方法。
下面是带有架构的架构表 1.帖子表
# 表名:posts # # id :integer not null, 主键 # 发布:字符串(255) # post_content :string(255) # created_at : 日期时间 # 更新时间:日期时间 #
class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
end
2.评论表
# 表名:cmets # # id :integer not null, 主键 # 评论:字符串(255) # post_id :整数 # created_at : 日期时间 # 更新时间:日期时间 # # 索引 # # index_cmets_on_post_id (post_id) #
class Comment < ActiveRecord::Base
belongs_to :post
end
现在,我想创建带有评论的帖子。我如何实现它?请帮忙。
表格部分
<%= form_for(@post) do |f| %>
<%= f.text_field :post %>
<%= f.text_field :post_content %>
<br>
<span>put comments</span>
<%= f.fields_for :comments do |s|%>
<%= s.text_field :comment %>
<%= s.hidden_field :post_id ,value: @post.id%>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
控制器代码
class PostsController < ApplicationController
def new
@post = Post.new
@post.comments.build
end
def create
@post = Post.new(post_params)
@post.comments.build
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
end
end
end
private
def post_params
params.require(:post).permit(:post,:post_content,comment_attributes:[:comment])
end
end
【问题讨论】:
-
第一步:在你的
PostsControllernew方法中添加这个@post = Post.new和@post.comments.build。 -
@Pavan,你能给我一些关于这个的教程或文件吗?
-
作为,我正在使用我正在使用与您所说的相同。但它使用 nil 来创建评论
-
您的
post_params应该是params.require(:post).permit(:post,:post_content,comments_attributes:[:comment])它是comments_attributes而不是comment_attributes -
我会添加它作为答案。
标签: ruby-on-rails