简体   繁体   中英

How do I get my controller to return just 2 attributes of an object in a json response?

So I would like to just get back the :id, :name attributes of my @neighborhood object in my json response.

This is my action in my controller:

  def autocomplete_neighborhood_name
    @neighborhood = Neighborhood.select("id, name").where("name LIKE ?", "#{params[:name]}%").order(:name).limit(10)

    respond_to do |format|
      format.json { @neighborhood :only => [:id, :name]}
    end    
  end

I am getting a syntax error on the format.json... line.

How do I do accomplish what I want?

Thanks.

Edit 1

My real goal is to try and refactor this code, to use format.json and use the newer methods of Rails 3.2.x:

def autocomplete_neighborhood_name
  respond_with(
    Neighborhood.
      select("id, name").
      where("name LIKE ?", "#{params[:name]}%").
      order(:name).
      limit(10).
      as_json(:only => [:id, :name]))      
end

If you have any other suggestions for how I might do this better, I would appreciate the feedback.

尝试这个:

format.json { render json: @neighborhood , :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