All threads / why .limit not working with find_by

Ask A Question


You’re not receiving notifications from this thread.

why .limit not working with find_by

TG asked in Rails

am trying to retrieve date with @category = Category.find_by(slug: params[:slug]).limit(5) but i get undefine method .limit

find_by only returns the first object that matches your query. You're calling limit on an instance of your category model which causes this error. Try using Category.where instead, .where returns an array instead of an object.

I need to get that +1 feature added so I can +1 Andy's comment. :)

Thanks Chris! Thanks for all you do.

You're welcome! Thanks for being here! :D

Category.where would fail so am able to fix it with
also using find_by since am looking for only one record

@categories = Category.find_by(slug: params[:slug])
@category = @categories.products.paginate(:page => params[:page], :per_page => 20).order('created_at DESC')

For clarity, you might want to swap your variable names, because @categories is actual a single Category, and @category is an array of Categories.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 53,130+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.