Mysql 将sql查询中的JSON响应分配给Rails中的变量

Mysql 将sql查询中的JSON响应分配给Rails中的变量,mysql,ruby-on-rails,json,Mysql,Ruby On Rails,Json,我试图在我的rails应用程序中查询一个mysql数据库,其中包含我的吉他标签存档。我只是尝试查询数据库,将每个选项卡的id、艺术家、歌曲和url分配给TabsController中的一个变量,以显示在我的tab.html.erb视图中。以下是我的代码: class TabsController < ApplicationController def show @tabs = Tab.find_by_sql("Select * from gp

我试图在我的rails应用程序中查询一个mysql数据库,其中包含我的吉他标签存档。我只是尝试查询数据库,将每个选项卡的id、艺术家、歌曲和url分配给TabsController中的一个变量,以显示在我的tab.html.erb视图中。以下是我的代码:

    class TabsController < ApplicationController

        def show
           @tabs = Tab.find_by_sql("Select * from gp where artist='led zeppelin'")


           respond_to do |format|
             format.html # show.html.erb
             format.json { render json: @tabs} #  

           end  
        end

     end

我的查询成功了,在我看来,它显示了所有选项卡的json响应。我的挑战是将吉他标签id、艺术家、歌曲和url分配给不同的变量。我感觉解决方案会很简单,但我被难住了。

您告诉浏览器响应格式将是json,因此您无法以不同的格式设置。如果您只是想显示所有选项卡,为什么不简化操作:

def show
  @tabs = Tab.find_by_sql("Select * from gp where artist='led zeppelin'")
end
然后在show.html.erb中,它看起来与我假设的数据结构类似

<% @tabs.each do |tab| %>
  ID: <%= tab.id %>
  Artist: <%= tab.artist %>
  Song: <%= tab.song %>
  URL: <%= tab.url %>
<% end %>
class TabsController < ApplicationController
    def show
       @tabs = Tab.find_by_sql("Select * from gp where artist='led zeppelin'")


       respond_to do |format|
         format.html # show.html.erb
         format.json { render json: @tabs.map{|t| {:id => t.id, :artist => t.artist, ...}}} 
       end  
    end
 end