-1

I am using Rails 4 i am trying to set an api and i have a services controller where i def some methods like this:

def articles_stores
  @article = Store.find(params[:id])
  if @article.nil?
    render :json => {:error_msg => "Record not found",:error_code => 404,:success => false} 
  else
    render json: {article: @article.as_json({except: [:updated_at,:created_at]}),success: true}
  end
end

But for some reason it is not rendering the error the else part works fine y also have all the necessary routes Any help will be appreciated

joni
  • 5,402
  • 1
  • 27
  • 40
Jhon C
  • 3
  • 2

1 Answers1

0

@article.nil? will never be true if the article does not exist: Store.find(params[:id]) will already raise an exception if the record does not exist, and this than gets handled by rails automatically as a 404. If you want to return nil, use something like this:

Store.where(id: 10).first

# old, deprecated way:
Store.find_by_id(10)

Also see here.

Community
  • 1
  • 1
joni
  • 5,402
  • 1
  • 27
  • 40
  • It seems that it turns true but then when i enter a valid one it shows only the error – Jhon C Jun 03 '14 at 16:23
  • huh? when you enter a valid one, it should not show any error? – joni Jun 03 '14 at 16:24
  • well the idea is that when you get a valid record like 3 in this case it should return the json format of that article and if the id is not found render the error, but it just shows the render :json => {:error_msg => "Record not found",:error_code => 404,:success => false} which is pretty cool i was not able to o it but it just no renderin the json of the variale with the id – Jhon C Jun 03 '14 at 16:27
  • put a `p @article` before `if @article.nil?` and show me the logs – joni Jun 03 '14 at 16:33
  • this is what i got sorry if is not the correct info i am beginner at rails: Started GET "/services/articles/stores/3.json" for 127.0.0.1 at 2014-06-03 10:40:28 -0600 Processing by ServicesController#articles_stores as JSON Parameters: {"id"=>"3"} [1m[36mStore Load (0.2ms)[0m [1mSELECT "stores".* FROM "stores" WHERE "stores"."id" = 10 ORDER BY "stores"."id" ASC LIMIT 1[0m Completed 200 OK in 2ms (Views: 0.3ms | ActiveRecord: 0.2ms) – Jhon C Jun 03 '14 at 16:49