Rails 从 mysql2 渲染 html

Rails render html from mysql2

我想从 mysql2 渲染 html。怎么了? 这是错误代码

NoMethodError in Admin::Stores#index
Showing /home/rok/Development/Pan/app/views/admin/stores/index.html.erb 

第 15 行提出的地方:

undefined method `name' for #<Hash:0x007f627f0cf808>
Extracted source (around line #15):

    13   <% @store_list.each do |stores| %>
    14      <tr>
    15         <th><%= stores.name %> </th>
    16         <td><%= stores.address %></td>
    17         <th><%= stores.phone %></th>
    18      </tr>

这是我的查看代码
index.html.erb

  <% @store_list.each do |stores| %>
  <tr>
     <th><%= stores.name %> </th>
     <td><%= stores.address %></td>
     <th><%= stores.phone %></th>
  </tr>
  <% end %>

这是我的控制器代码

    class Admin::StoresController < ApplicationController
      $client = Mysql2::Client.new(:host => "localhost", :username => "rok", :password => "xxxxxx@", :database => "Pan_development")

      def index
        @store_list = $client.query('select * from stores')
      end

    end

我的路线

namespace :admin do
  resources :stores
end

耙路

admin_stores GET    /admin/stores(.:format)           admin/stores#index
             POST   /admin/stores(.:format)           admin/stores#create
new_admin_store GET    /admin/stores/new(.:format)       admin/stores#new
edit_admin_store GET    /admin/stores/:id/edit(.:format)  admin/stores#edit
admin_store GET    /admin/stores/:id(.:format)       admin/stores#show
             PATCH  /admin/stores/:id(.:format)       admin/stores#update
             PUT    /admin/stores/:id(.:format)       admin/stores#update
             DELETE /admin/stores/:id(.:format)       admin/stores#destroy

问题

undefined method `name' for #<Hash:0x007f627f0cf808>

查看您的错误消息,stores 是一个哈希。您无法使用 . 运算符访问散列 key/value。

解决方案

您应该可以使用 stores[:name]stores['name] 访问商店的 name。请参阅 documentation 了解如何检索哈希中的键的值。

所以,这应该可以解决您的问题:

<% @store_list.each do |stores| %>
    <tr>
      <th><%= stores['name'] %> </th>
      <td><%= stores['address'] %></td>
      <th><%= stores['phone'] %></th>
    </tr>
<% end %>