Top > Ruby on Railsあれこれ > 直打ちSQLで一覧表示
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
<html>
<head>
  <title>Tutorial: Employee List (Direct SQL)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <%= stylesheet_link_tag 'ror' %>
</head>
<body>
<h2>Tutorial: Employee List (Direct SQL)</h2>
 
<table border="1">
  <tr style="background-color:pink">
    <th>Id</th><th>Name</th><th>JobType</th><th>Salary</th><th>Department</th>
  </tr>
  <% for e in @employees %>
  <tr style="background-color:<%= cycle('white', 'yellow') %>">
    <td align="right"><%=h e.id %></td>
    <td><%=h e.name %></td>
    <td><%=h e.job_type %></td>
    <td align="right"><%= number_with_delimiter(e.salary, delimiter=",") %></td>
    <td><%= e.department_name %></td>
  </tr>
  <% end %>
</table>
</body>
</html>
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
class DirectSqlController < ApplicationController
  
  #一覧画面表示
  def index
    
    sql = <<-EOS
      select e.id, e.name, e.salary, e.department_id, e.job_type, d.name as department_name 
        from employees e
        inner join departments d on d.id = e.department_id
        order by e.id
    EOS
    
    @employees = Employee.find_by_sql(sql)
    render :action => 'index.html.erb'
  end
  
end
  0
  1
  2
  3
  4
  5
  6
e = employees[0]
puts e.id # ← e.id
puts e.name # ← e.name
puts e.salary # ← e.salary
puts e.department_id # ← e.department_id
puts e.job_type # ← e.job_type
puts e.department_name # ← d.name as department_name
  0
  1
class Employee < ActiveRecord::Base
end

添付ファイル: filedb_tuto_dsql_1.jpg 287件 [詳細]

リロード   新規 編集 凍結解除 差分 添付 複製 名前変更   ホーム 一覧 単語検索 最終更新 バックアップ リンク元   ヘルプ   最終更新のRSS
Last-modified: 2012-08-08 (水) 23:25:46 (2925d)