[英]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. 我正在使用活动模型序列化器gem,并且需要通过参数来限制json响应。
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. 只需直接传递params [:limit]即可。
def index
@page = Page.limit(params[:limit])
end
If params[:limit] isn't defined (nil), it'll just return all of the records. 如果未定义params [:limit](nil),它将仅返回所有记录。 You don't even need to convert it to an integer. 您甚至不需要将其转换为整数。 Rails does it for you! Rails为您做到!
UPDATE 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): 如果您真的想检查未传递非数字,则可以在Page类中创建自己的limit类方法(未经测试,但应该可以使用):
class Page << ActiveRecord::Base
def self.limit(num = nil)
num = num.to_i > 0 ? num : nil
super(num)
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.