rails_antipatternsについて書いていきます

<html>
<body>
  <ul><% User.find(:order => "last_name").each do |user| -%>
      <li><%= user.last_name %> <%= user.first_name %></li>
    <% end %>
  </ul>
</body>
</html>
  • View内で直接DBにアクセスすべきでない

[Try1] move the logic into the Controller

1 class UsersController < ApplicationController
2   def index
3     @users = User.order("last_name")
4   end
5 end
<html>
<body>
  <ul>
    <% @users.each do |user| -%>
      <li><%= user.last_name %> <%= user.first_name %></li>
    <% end %>
  </ul>
</body>
</html>

AntiPattern

  • DBのfinderはModelで記述すべき

[Try2] move the direct find call down into the Model

1 class UsersController < ApplicationController
2   def index
3     @users = User.ordered
4   end
5 end
1 class User < ActiveRecord::Base
2   def self.ordered
3     order("last_name")
4   end
5 end

railsではさらに美しく記述できる機能が用意されている

[try3] use the named scpoe of rails

1 calss User < ActiveRecord::Base
2   scope :orderd, order("last_name")
3 end

ちょーきもちー




comments powered by Disqus


© 2015 kyuden