0

I am having two model post and product

This is my post controller

before_action :seo_url,only: [:show]
def product_list
    if params[:product_id] == 1
      @products = Product.All
    end
    respond_to do |format|
      format.json { render json: @products.id }
    end
  end

private
def seo_url
    @post = Post.friendly.find params[:id]
  end

Here is my ajax call

$.ajax({
    type: "GET",
    url: '/posts/product_list.json',
    data: {product_id: 1},
    dataType: 'json'
});

My console throwing something like this. I cant understand what is happening can anyone help

Parameters: {"product_id"=>"1", "_"=>"1380659219433", "id"=>"product_list"}
  Post Load (0.9ms)  SELECT "posts".* FROM "posts" WHERE "posts"."slug" = 'product_list' ORDER BY "posts"."id" ASC LIMIT 1
Completed 404 Not Found in 5ms

ActiveRecord::RecordNotFound (ActiveRecord::RecordNotFound):
  app/controllers/posts_controller.rb:85:in `seo_url'

Edit-1

Processing by PostsController#product_list as JSON
  Parameters: {"product_id"=>"1"}
Completed 500 Internal Server Error in 3ms

NoMethodError (undefined method `id' for nil:NilClass):
4

2 回答 2

1

/posts/product_list is being interpreted as "call the show method in the controller with an id of "product_list" rather than "call the product_list method".

This is because of your config/routes.rb file. You need to tell it about your product_list method. Something like this:

resources :posts do
  get "product_list", on: :collection
end
于 2013-10-01T20:39:51.790 回答
0

There are a few non-standard concepts in your code.

The simple answer to your questions is the a Post with id = "product_list" cannot be found. I'm assuming that you've changed your primary key from id?

Check out the ActiveRecord documentation - http://guides.rubyonrails.org/active_record_querying.html#retrieving-a-single-object

The long answer would involve asking why your RESTful get route has the id of "product_list". I would re-visit http://guides.rubyonrails.org/routing.html and double check your routes before you continue.

于 2013-10-01T20:49:14.300 回答