【发布时间】:2015-06-07 16:24:40
【问题描述】:
我有 2 个模型 Post 和 Comment,其中 Post 有很多 Comments 和 Comment belongs_to Post。 为该帖子创建帖子和 cmets 时一切正常。
现在我有一个要求,当我在帖子/显示页面中单击“创建新评论”时,我想以模式显示 cmets/_form。
cmets_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
posts/show.html.erb:
<%= link_to 'New Coment', new_post_comment_path(@post), :id => 'create_comment' %>
cmets/new.html.erb:
<div id="content">
<h1>New Comment</h1>
<%= render 'form' %>
</div>
cmets/_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 %>
cmets/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 %>
我不知道我哪里出错了。当我点击“创建评论”时,它会重定向到新页面而不是弹出模型,甚至无法创建评论。
请帮忙。
【问题讨论】:
-
请查看 Bootstrap 3,它将指导您如何在应用程序中使用模态
-
@AmitSharma : 你能提供任何有用的链接
标签: javascript jquery ruby-on-rails modal-dialog