【问题标题】:Ruby / Rails: Respond to json request, create array of hashes from array of objects, change the name of a keyRuby / Rails:响应json请求,从对象数组创建哈希数组,更改键名
【发布时间】:2011-08-24 22:00:22
【问题描述】:

我正在使用CodeNothing's jQuery Autocomplete 插件来启用文本输入的自动完成功能。

插件需要获取一个json对象,格式如下:

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

所以,我的 Tag 模型将其名称存储为 name,而不是 value。为了响应这个 ajax 请求,我创建了以下 tags#index 操作:

def index
    @tags = Tag.where("name LIKE ?", "%#{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

这是我能想到的最好的了。它有效,但看起来很笨拙。

是否有更快或更好的方法将带有name 方法的标签数组转换为带有{ :value =&gt; tag.name } 形式的哈希数组?

另外,对于奖励积分,您能否建议对此控制器操作进行任何改进?

谢谢!


注意

我最终受到了 Deradon 的回答的启发,并提出了这个最终实现:

在我的 Tag 模型中我添加了:

def to_value
    { :value => name }
end

然后在我的控制器中我简单地调用了:

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

很好,简短,简单。我对此感到高兴得多。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ajax ruby-on-rails-3 json


    【解决方案1】:

    如果我必须重构这个,我会这样做:

    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:另一种可能有效但未经测试的方法。现在这里没有 Ruby

    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
    

    【讨论】:

    • 我没有完全使用这个,但你给了我一个好主意。请参阅原始问题的注释。感谢您的帮助!
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2012-03-27
    • 2015-04-19
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多