anndrew78
anndrew78

Reputation: 196

Rails 5(ajax): wrong number of arguments (given 1, expected 0)

I was trying to create associated model Comment for Post via ajax in Rails 5, but get the error.

ArgumentError in Posts#show

Showing /home/mnml/rails/ajax-app/app/views/comments/_form.html.erb where line #2 raised:

wrong number of arguments (given 1, expected 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

posts/show.html.erb

<%= render "comments/form"%>

comments/_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>

comments/create.js.erb

$('#comments').prepend('<%= j render(@comment) %>')

Where I do my mistake? Thanks for help

Upvotes: 0

Views: 2339

Answers (1)

fl9
fl9

Reputation: 434

You need to call form_with like this in your _form.html.erb file

<%= form_with model: [@post, @post.comments.build], id: :new_comment do |form| %>

Upvotes: 1

Related Questions