【发布时间】:2017-08-21 18:55:31
【问题描述】:
我有一个关于带有嵌套资源的 form_for 的问题。我创建了类似博客的东西,在 cmets 上有帖子、cmets、cmets(如回复)。我有一个问题。然后我尝试发表评论:“重定向到http://localhost:3000/ 过滤器链因 :get_parent 呈现或重定向而停止 已完成 302 找到”
用于 cmets 的 new.html.erb:
<div class= "container" %>
<%= form_for @comment do |f| %>
<%= f.input :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
</div>
我的 cmets 控制器:
before_filter :get_parent
def new
@comment = @parent.comments.build
end
def create
@comment = @parent.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to posts_path(@comment.post), :notice => 'Thank you for your comment!'
else
render :new
end
end
private
def comment_params
params.require(:comment).permit(:body, :title, :user_id, :commentable_id, :commentable_type)
end
def get_parent
@parent = Post.find_by_id(params[:post_id]) if params[:post_id]
@parent = Comment.find_by_id(params[:comment_id]) if params[:comment_id]
redirect_to root_path unless defined?(@parent)
end
end
后模型:
has_many :comments, as: :commentable
belongs_to :user
def post
commentable.is_a?(Post) ? commentable : commentable.post
end
评论模型:
belongs_to :user
belongs_to :commentable, polymorphic: true
has_many :comments, :as => :commentable
路线:
resources :posts do
resources :comments
end
resources :comments do
resources :comments
end
post_show.html.erb
<h1><%= @post.title %></h1>
<div class="body">
<%= @post.body %>
</div>
<h2>Comments</h2>
<p><%= link_to 'Add a Comment', new_post_comment_path(@post) %></p>
<ul class="comment_list">
<%= render :partial => 'comments/comment', :collection => @post.comments %>
</ul>
带有应用程序的github repo:https://github.com/Dmitry96/dasasd
【问题讨论】:
标签: ruby-on-rails ruby