rmosolgo
rmosolgo

Reputation: 1874

Rails/ActiveRecord Model.Find returns the wrong record

This is the wackiest.

When I visit:

/ingredients/14.json

I get

{ id: 13,
  name: "Tomato",
  category: "Vegetable",
  created_at: "2013-11-20T04:35:36.704Z",
  updated_at: "2013-11-20T05:59:34.444Z"
}

And in the logs:

Started GET "/ingredients/14.json" for 127.0.0.1 at 2013-11-19 22:02:35 -0800
Processing by IngredientsController#show as JSON
  Parameters: {"id"=>"14"}
  Ingredient Load (0.4ms)  SELECT "ingredients".* FROM "ingredients" WHERE (14) LIMIT 1
#<Ingredient id: 13, name: "Tomato", category: "Vegetable", created_at: "2013-11-20 04:35:36", updated_at: "2013-11-20 05:59:34">
Completed 200 OK in 18ms (Views: 0.2ms | ActiveRecord: 0.6ms)

There are only two items in the database, #13 (tomato) and #14 (egg).

I'm using:

I have no idea what this could be? Any guesses?!

Update

It was just me being an idiot. Check out my bad controller action code:

  def show
    @resource = @class.find_by(params[:id])
    respond_with @resource
  end

of course, this should be:

  def show
    @resource = @class.find(params[:id])
    respond_with @resource
  end

Thank you!

Upvotes: 1

Views: 402

Answers (1)

Chandranshu
Chandranshu

Reputation: 3669

Yes, your generate SQL is wrong. The query generated is:

SELECT "ingredients".* FROM "ingredients" WHERE (14) LIMIT 1

whereas it should have been:

SELECT "ingredients".* FROM "ingredients" WHERE id = 14 LIMIT 1

Since the condition in the first where clause always evaluates to true, it picks up 1 row randomly. Which row gets picked up depends on how your DBMS stores data internally.

To know why the generated query is wrong, we'll need to see the code in your Controller's action.

Upvotes: 2

Related Questions