简体   繁体   中英

view don't render json appropriately

I using rails 4.0.0 and ruby 2.0.

My model Country has 3 attributes: id, name:string and flag:string.

The controller:

...
respond_to :html, :json
def index
  @countries = Country.all      
  respond_whit @countries.as_json(only: [:id, :name])
end

So, when I access countries.json in the browser it's show all attributes instead only id and name. I already tried redefine the method as_json like this:

def as_json(options = nil)
  {id: id, text: name}
end

but didn't work too.

Curiously, when I run as_json in the console it's work perfectly.

What is missing to work?

You can use jbuilder to show the specific attributes

json.companies @companies.map { | company |

  {
    id: company.id,
    text: company.name

  }
}

关于什么

respond_with @countries, only: [:id, :name]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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