【问题标题】:use JSON object with rails scoped使用带有 Rails 范围的 JSON 对象
【发布时间】:2012-10-22 03:34:04
【问题描述】:

我希望以下事情发生:

当我选择一个选择框时,我希望它通过 AJAX 向我的控制器发送一个 JSON 对象,如下所示:

        var encoded = $.param(data);            
        jQuery.ajax ({
            url: '/trips',
            type: 'GET',
            data: {'toSearch' : encoded},
            success: function (response) {
                //succes
                console.log(encoded);
            }
        });

并像这样将这些用作我的查询的参数

respond_to :json, :html

  def index
    @trips = Trip.scoped
    @trips.where("category_id = ?", params[:category_ids]) if params[:category_ids] # category_ids = array; select * from trips where category_id IN [1,3,4]


    respond_with @trips
  end

我该怎么做?以及序列化我的 JSON 对象的最佳方式是什么?

【问题讨论】:

    标签: javascript ruby-on-rails ajax json params


    【解决方案1】:

    您可以执行以下操作:

    def index
      @trips = Trip.scoped
      @trips.where("category_id = ?", params[:category_ids]) if params[:category_ids] # category_ids = array; select * from trips where category_id IN [1,3,4]
    
      respond_to do |format|
        format.html # index.html.erb
        format.xml  { render :xml => @trips }
        format.json { render :json => @trips }
      end
    end
    

    那么你应该在 javascript 回调中做任何你想做的事情。

    编辑

    如果您只想要 json 格式,您可以执行以下操作:

    render :json => @trips
    

    您也可以查看Layouts and Rendering in Rails 指南。

    【讨论】:

    • 我没有足够的声誉来做这件事。
    猜你喜欢
    • 1970-01-01
    • 2013-08-12
    • 2011-10-09
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多