我很新的軌道。我正在學習如何將數據庫查詢傳遞給json以在視圖中呈現它們。顯示數據庫表中的所有記錄,而不是單個記錄
我想執行一個簡單的表查詢(表稱爲user
name:string
id:integer
),其在所述模型中進行,並傳遞給控制器,然後到index.json.jbuilder
到index.html.erb.
的問題是,當我請
blabla/index.json
我得到一個空數組,但是當我打電話blabla/1.json
,我得到的用戶1的數據,但我希望得到所有用戶。
我知道有更簡單的方法來做到這一點,但這是我想如何做到這一點。我如何避免傳遞user_id來獲取記錄?
user.rb
class User < ActiveRecord::Base
def self.feed
"SELECT * FROM User"
end
end
users_controller.rb
def index
@users = User.feed
end
index.json.jbuilder
json.extract! @user, :id, :name, :created_at, :updated_at
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Listing Users</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New User', new_user_path %>
只是聲明一個變量傳遞給json。這是不正確的? –
你的索引方法在哪裏? –
控制器顯示是一個錯字。現在糾正了。同樣的問題,雖然 –