【问题标题】:Returning ActiveRecord::Relation as json to an ajax call in rails将 ActiveRecord::Relation 作为 json 返回到 rails 中的 ajax 调用
【发布时间】:2013-03-13 14:46:28
【问题描述】:

我的问题可能有一个简单的解决方案,但密集的谷歌搜索却一无所获。

我有一个 ajax 调用:

$.get(path,{ section_id: "a", field_id: "b"})
 .done(function(data) {alert(data);})
 .fail(function() { alert("error"); });

这个 ajax 调用转到指定的控制器并执行一个查询,返回一个 ActiveRecord::Relation 对象。到现在为止还挺好。 现在,我想做的是将此 ActiveRecord::Relation 对象作为 json 返回到 done 函数。我怎样才能做到这一点? 感谢所有帮助者!

【问题讨论】:

    标签: ruby-on-rails ajax json activerecord


    【解决方案1】:

    我假设您想从关系中返回一个对象,而不是活动记录类。在您的控制器中,您应该以适当的格式呈现您的对象,例如:

    respond_to do |format|
        format.json { render json: @your_object}
    end
    

    【讨论】:

      【解决方案2】:

      如果您想返回 ActiveRecord::Relation 对象中使用的条件哈希,您可以这样做:

      @relation.where_values_hash.to_json

      【讨论】:

        【解决方案3】:

        做这样的事情

        @post = Post.where(id: params[:id])
        # @post at the moment is an AR::Relation
        render json: @post, status: :ok
        

        实际上只会返回序列化为 JSON 的记录。实际上,您可以通过执行以下操作在 Rails 控制台中对此进行测试:

        @record = YourModel.where(some_condition: some_parameter)
        @record.class #=> ActiveRecord::Relation
        @json_record = @record.to_json
        @json_record.class #=> String
        # @json_record will be the JSON representation of whatever the Relation fetched for you.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-29
          • 1970-01-01
          • 2011-08-01
          • 2013-02-18
          相关资源
          最近更新 更多