简体   繁体   中英

Rails ajax ActionController::Parameters permitted: false

I'm trying to do a Ajax call that return all of my reviews when click on a link. When I click on the link I'm calling to a method of User model passing a parameter and I receiving this error <ActionController::Parameters {"controller"=>"users", "action"=>"show_all_reviews"} permitted: false>

My user_controller:

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @my_reviews = @user.my_reviews.where.not(comment: [nil, ""])
    @my_reviews = @my_reviews.paginate(:page => params[:page], :per_page => 1)
    @friends = @user.get_friends_list
  end

  def show_all_reviews
    @user = User.find(params[:user_id])
    @my_reviews = @user.my_reviews.where.not(comment: [nil, ""])
  end

  private

  def user_params
    params.require(:user).permit(:description, :phone)
  end
end

That's my button that do the Ajax call <%= link_to 'Mostrar todos los comentarios', '#', remote: true, id: 'show_more_link', data: {user: @user.id} %>

And my jquery function:

$('#show_more_link').on('click', function(event) {
  event.preventDefault();
  var user_id = $(this).data("user");
  console.log(user_id);
  $.ajax({
    url: "/show_all_reviews",
    type: "POST",
    data: {
      "user_id": user_id,
    },
    dataType: "json",
    success: function(data) {
      alert('done');
    }
  });
});

I add this to routes.rb

get '/show_all_reviews', to: 'users#show_all_reviews', as: :show_all_reviews

You made a mistake. Change type to GET inside your ajax code. As I see in your routes the custom action with GET type.

Or you can also modify approach here. Use namespace. in your routes.rb add:

namespace :users, path: nil, as: nil do
  resources :users, only: [] do
    resources :reviews, only: :index
  end
end

create new folder under controllers /users. Add new controller there:

controllers/users/reviews_controller.rb

 class Users::ReviewsController < ApplicationController
   def index
    @user = User.find(params[:user_id])
    @reviews = @user.my_reviews.where.not(comment: [nil, ""])

    render json: @reviews
   end
 end

inside view file:

 <%= link_to 'reviews', user_reviews_path(user), remote: true %>

You don't need to use $.ajax() . This can be done in simple way: -

Route: -

get '/show_all_reviews/:user_id', to: 'users#show_all_reviews', as: :show_all_reviews

Add path to link_to including remote: true

<%= link_to 'Mostrar todos los comentarios', show_all_reviews_path(user_id: @user.id), remote: true, id: 'show_more_link' %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM