简体   繁体   English

Rails渲染页面为json

[英]rails render page as json

How to render page as json correctly 如何正确将页面呈现为json

my chunk of code 我的代码块

respond_to :html, :xml, :json


  def getOffersByURL
   @my_model= Mymodel.where(attr1: params[:url], :validFrom => {:$lte => Time.now}).all
   respond_with @my_model
  end

When in trying to do like this nothing happens 当试图这样做时,什么也没有发生

http://0.0.0.0:3000/getOffersByURL?url=some_data.xml 

or 要么

http://0.0.0.0:3000/getOffersByURL?url=some_data.json

concretely it comes like this 具体来说就是这样

Processing by MyController#getOffersByURL as HTML
  Parameters: {"url"=>"some_data.xml"}

Try to change your function: 尝试更改您的功能:

def getOffersByURL
  @my_model= Mymodel.where(attr1: params[:url], :validFrom => {:$lte => Time.now}).all
  respond_to do |format|
    format.json {
        render json: @my_model
    }
    format.html {
        @my_model
    }
    end
end

What happens if you try to show your json like this in your view: 如果尝试在视图中显示这样的json会发生什么:

<%= @my_model.to_json %>

Do you have any data checking the page in the browser? 您是否有任何数据在浏览器中检查页面? Open the developers tool and try to find if the object brings any data... 打开开发人员工具,然后尝试查找对象是否带来任何数据...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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