简体   繁体   中英

How to check if params exist in rails controller?

This works, but feels klunky. Is there a more rails-y way to limit a collection based on params? I'm using active model serializers gem and need the json response to be limited via the params.

def index    
 if params.has_key?(:limit)
   limit = params[:limit].to_i
   @pages = Page.all.take(limit)
 else
   @pages = Page.all
 end
end

If I use the following, I receive error messages when passing a string or nothing to the limit params.

def index
 @pages = Page.limit(params[:limit])

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @pages }
 end

end

Thanks!

You shouldn't have to do anything. Just pass params[:limit] in directly.

def index
  @page = Page.limit(params[:limit])
end

If params[:limit] isn't defined (nil), it'll just return all of the records. You don't even need to convert it to an integer. Rails does it for you!

UPDATE

If you really want to check that non-numbers aren't being passed in, you could create your own limit class method in your Page class (not tested, but should work):

class Page << ActiveRecord::Base

  def self.limit(num = nil)
    num = num.to_i > 0 ? num : nil
    super(num)
  end

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM