开发者

Ruby / Rails: Respond to json request, create array of hashes from array of objects, change the name of a key

开发者 https://www.devze.com 2023-03-30 06:31 出处:网络
I\'m using CodeNothing\'s jQuery Autocomplete plugin to enable autocomplete on a text input. The plugin needs to retreive a json object in the form:

I'm using CodeNothing's jQuery Autocomplete plugin to enable autocomplete on a text input.

The plugin needs to retreive a json object in the form:

[{ value: 'something' }, { value: 'something else' }, { value: 'another thing' }]

So, my Tag model stores its name as name, not value. To respond to this ajax request I created the following tags#index action:

def index
    @tags = Tag.where("name 开发者_如何学GoLIKE ?", "%#{params[:value]}%")
    @results = Array.new
    @tags.each do |t|
        @results << { :value => t.name }
    end
    respond_to do |format|
        format.json { render :json => @results }
    end
end

This is the best I could think of. It works, but it seems cludgey.

Is there a faster or better way to convert an array of Tags with a name method to an array of hashes with the form { :value => tag.name }?

Also, for bonus points, can you suggest any improvements to this controller action?

Thanks!


Note

I ended up being inspired by Deradon's answer and came up with this final implementation:

In my Tag model I added:

def to_value
    { :value => name }
end

Then in my controller I simply called:

def index
    @tags = Tag.where("name LIKE ?", params[:value]+"%" )
    respond_to do |format|
        format.js { render :json => @tags.map(&:to_value) }
    end
end

Nice, short, simple. I'm much happier with it. Thanks!


If I had to refactor this, I'd do it this way:

def index
    tags = Tag.where(:name => params[:value])
    @results = tags.each.inject([]) do |arr, tag|
        arr << { :value => tag.name }
    end
    respond_to do |format|
        format.json { render :json => @results }
    end
end

edit: another way that might work, but untested. No Ruby here right now

def index
    @tags = Tag.where(:name => params[:value])
    @tags.collect!{ |tag| {:value => tag.name} }
    respond_to do |format|
        format.json { render :json => @tags }
    end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消