Ask A Question

Notifications

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

Reply

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.

Reply

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

Reply

Thanks Chris! Thanks for all you do.

Reply

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

Reply

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')

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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