User7777
User7777

Reputation: 299

Ajax request not working for controller action in rails

I am trying to generate an ajax request to call the blog controller count action but I am getting an error and I am not able to figure out the reason. Please help me find it. Below is the code with the error.

blogs_controller.rb

  def count
    @blog = Blog.find(params[:blog_id])
    @blog.increment!(:blog_count)
    redirect_back(fallback_location: blogs_path)
  end

show.html.erb

<button onclick="CountFun()" class="btn btn-success float-right" id="first" >Copy</button>

<script>
 $('#first').click(function(e) {
     e.preventDefault();
   $.ajax({
    type: "PUT",
    url: "#{blog_count_path(@blog)}"
  });
 });
</script>

Error message

ActionController::ParameterMissing (param is missing or the value is empty: blog):

app/controllers/blogs_controller.rb:79:in blog_params' app/controllers/blogs_controller.rb:45:inblock in update' app/controllers/blogs_controller.rb:44:in `update'

Just for test whether I had defined the controller action in the correct way I had this add this link_to button just to see if it works and it works like a champ it just that the I am getting an error with the ajax request.

<%= link_to 'Count', blog_count_path(@blog), method: :put, id: 'second' %>

routes.rb

resources :blogs, path: '/' do
 put :count
end

Upvotes: 2

Views: 852

Answers (2)

Roland Studer
Roland Studer

Reputation: 4415

Your problem is in a different place than you think, the path and the action is corrrect, but your script does not have the right path, because you did just pass it #{blog_count_path(@blog)}. erb does not see anything to parse there.

So your in your show.html.erb you need to make sure you erb knows you want to replace something:

$.ajax({
  type: "PUT",
  url: "<%= blog_count_path(@blog) %>"
});

A better way would to forget about the script entirely and direct create a button with remote: true

<%= button_to "Count", blog_count_path(@blog), method: :put, remote: true %>

Upvotes: 1

lacostenycoder
lacostenycoder

Reputation: 11226

Use a post or put route. You don't have a view to render so just do this in your controller action.

def count
  @blog = Blog.find(params[:blog_id])
  if @blog && @blog.increment!(:blog_count)
    render json: { data: 'OK', status: 200 }
  else
    render json: { error: "blog did not increment" }, status: :unprocessable_entity
  end
end

Upvotes: 1

Related Questions