V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
androidBrant
V2EX  ›  程序员

Rails菜鸟求助,关于api接口

  •  
  •   androidBrant · 2013-08-17 15:59:00 +08:00 · 3183 次点击
    这是一个创建于 3876 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假设我有一个Joke的model和controller,我要做一个接口给移动端调用(返回xml),我想以分页的形式(即请求参数中传过来page和pageCount)返回数据,我在controller中定义了
    def getJokeByPageAndPageCount

    end
    这个方法,后面怎么做,把路由设到这个方法,如何分离出page和pageCount参数。。。


    完全的web菜鸟,帮忙,Thank you
    6 条回复    1970-01-01 08:00:00 +08:00
    leiz
        1
    leiz  
       2013-08-17 16:49:50 +08:00
    # route.rb
    match '/get_joke' to: 'jokes#getJokeByPageAndPageCount', via: 'get' # or post

    # jokes_controller.rb
    def getJokeByPageAndPageCount
    # do whatever you want
    respond_to do |format|
    format.xml { # send whatever you want }
    end
    end
    leiz
        2
    leiz  
       2013-08-17 16:52:07 +08:00
    # jokes_controller.rb

    def getJokeByPageAndPageCount
    # ...
    page = params[:page]
    page_count = params[:PageCount]
    rails3
        3
    rails3  
       2013-08-17 16:53:58 +08:00
    @per_page = 10
    users = User.paginate(:page => params[:page], :per_page => @per_page)
    users_count = User.all.count
    @page_count = users_count % @per_page == 0 ? users_count % @per_page : users_count % @per_page + 1
    respond_to do |format|
    format.html # index.html.erb
    format.xml { render xml: {:page_count => @page_count, :users => users}.to_xml }
    end
    androidBrant
        4
    androidBrant  
    OP
       2013-08-17 17:49:09 +08:00
    @leiz
    @rails3 Great, thank you
    androidBrant
        5
    androidBrant  
    OP
       2013-08-17 18:38:37 +08:00
    @leiz
    @rails3

    page和page_count如何传参?http://localhost:3000/api/getJokeByPageAndPageCount?page=0 这样不行

    我的路由
    match '/api/getJokeByPageAndPageCount', to: 'jokes#getJokeByPageAndPageCount', via: 'get'
    leiz
        6
    leiz  
       2013-08-17 18:52:49 +08:00
    @androidBrant
    这个问题和rails无关,你先去看看 html form, ajax
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   952 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 21:34 · PVG 05:34 · LAX 14:34 · JFK 17:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.