Rails Rendering a partial within JSON

前端 未结 3 500
挽巷
挽巷 2021-01-26 12:37

I am trying to render a partial inside a JSON file so that I can use it via AJAX. Currently in my JSON file I have:

<% self.formats = [\"html\"]%>
{
   \"h         


        
3条回答
  •  盖世英雄少女心
    2021-01-26 13:36

    You need to change your controller. In the respond_to part you need to add json rendering. Like this:

    respond_to do |format|
         format.json { render :json => @instancevar }
         ....
         ...
         ..
    end
    

    Then you can simply add .json to your url and you will receive the data formated as json. What you might need to do is disabeling the JSON root hich is automaticly added by default. Just add this line to your environment (development.rb, production.rb,...) configuration:

    config.active_record.include_root_in_json = false
    

    This is important when you are parsing the json.

提交回复
热议问题