我试图在Rails 5中通过ajax创建关联模型Comment for Post,但是得到了错误。
帖子中的ArgumentError#show
显示/home/mnml/rails/ajax-app/app/views/comments/_form.html.erb第2行:
错误的参数数量(给定1,预期为0)
的routes.rb
resources :posts, only: [:new, :create, :show, :destroy] do
resources :comments, only: [:new, :create, :show, :destroy]
end
post.rb
belongs_to :user
has_many :comments
comment.rb
belongs_to :user, optional: true
belongs_to :post
posts_controller.rb
def show
@post = Post.find(params[:id])
@comment = @post.comments.build
@comments = @post.comments
end
comments_controller.rb
def new
@post = Post.find(params[:post_id])
@comment = @post.comments.build
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
respond_to do |format|
if @comment.save
format.html { redirect_to @comment.post, notice: 'Comment was successfully created.' }
#format.json { render @comment, status: :created, location: @comment }
format.js
else
format.html { render :new }
format.json { render json: @comment.errors.full_messages, status: :unprocessable_entity }
end
end
end
private
def comment_params
params.require(:comment).permit(:description)
end
文章/ show.html.erb
<%= render "comments/form"%>
评论/ _form.html.erb
<form>
<%= form_with [@post, @post.comments.build], id: :new_comment do |form| %>
<div class="form-group">
<%= form.label :description %>
<%= form.text_field :description, id: :comment_description, class: "form-control" %>
</div>
<div class="form-group">
<%= form.submit "Comment it", class: "btn btn-default", data: { "disable-with": "Comment is saving..." } %>
</div>
<% end %>
</form>
评论/ create.js.erb
$('#comments').prepend('<%= j render(@comment) %>')
我犯错误的地方?谢谢你的帮助
答案 0 :(得分:1)
您需要在form_with
文件
_form.html.erb
这样的内容
<%= form_with model: [@post, @post.comments.build], id: :new_comment do |form| %>