我有2个模型帖子和评论,其中帖子有很多评论和评论belongs_to Post。 每件事都可以为这些帖子创建帖子和评论。
现在我有一个要求,当我点击"创建新评论"在帖子/节目页面中,我想以模态显示评论/ _form。
comments_controller.rb:
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
respond_with(@comments)
end
# GET /comments/1
# GET /comments/1.json
def show
respond_with(@comments)
end
# GET /comments/new
def new
@post = Post.find(params[:post_id])
@comment = @post.comments.build
end
# GET /comments/1/edit
def edit
@post = Post.find(params[:post_id])
end
# POST /comments
# POST /comments.json
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to(@comment, :notice => 'Article was successfully created.') }
format.xml { render :xml => @comment, :status => :created, :location => @comment }
format.js
else
format.html { render :action => "new" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
format.js
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
@post = Post.find(params[:post_id])
@comment.update(comment_params)
redirect_to post_path(@post)
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:commenter, :description)
end
end
帖/ show.html.erb:
<%= link_to 'New Coment', new_post_comment_path(@post), :id => 'create_comment' %>
评论/ new.html.erb:
<div id="content">
<h1>New Comment</h1>
<%= render 'form' %>
</div>
评论/ _form.html.erb:
<%= form_for([@post, @comment], :remote => true) do |f| %>
<div class="field">
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
评论/ create.js.erb:
<%- if @comment.errors.any? %>
console.log('Error');
$('#dialog-form').html('<%= escape_javascript(render('form')) %>');
<%- else %>
console.log('Created');
$('#dialog-form').dialog('close');
$('#dialog-form').remove();
$('table').append('<%= escape_javascript(render(@comment)) %>');
<%- end %>
我不知道哪里出错了。当我点击&#34;创建评论&#34;它重定向到新页面而不是弹出模型,甚至无法创建评论。
请帮忙。
答案 0 :(得分:2)
示例:
<%= link_to 'Show Modal', "#", data: {toggle: "modal", target: "#modal"} %>
隐藏的部分
<div class="modal hide fade" id="modal" title="My modal">
/* your comment form */
/* render comment form */
</div>
只需确保目标是您隐藏的部分ID。