Rails Best Practiceを読む

過剰なルーティングのカスタマイズ

元記事はこちら 翻訳 Bad Smell map.resources :posts, :member => { :comments => :get, :create_comment => :post, :update_comment => :put, :delete_comment => :delete } Roy Fielding’*1の論文*2によると、リソースと、その状態を表すには、RESTful…

RESTfulにするならデフォルトのルーティングを使わない

元記事はこちら 感想 内容がRails2の時代のものでRails5と書き方が大きく異なるので、翻訳は割愛。 RESTfulなルーティングを採用する場合は、余計なルーティングが生成されると、セキュリティリスクにもなるからやめましょうという主旨だと思う。 resources …

入れ子モデルフォーム

元記事はこちら 翻訳 Bad Smell class Product < ActiveRecord::Base has_one :detail end class Detail < ActiveRecord::Base belongs_to :product end <% form_for :product do |f| %> <%= f.text_field :title %> <% fields_for :detail do |detail| %> <…

無駄に深いネスト

元記事はこちら 翻訳 Bad Smell map.resources :posts do |post| post.resources :comments do |comment| comment.resources :favorites end end <%= link_to post_comment_favorite_path(@post, @comment, @favorite) %> 3階層にネストしたルーティングは本…

model.collection_model_ids (多対多)

元記事はこちら 翻訳 Bad Smell class User < ActiveRecord::Base has_many :user_role_relationships has_many :roles, :through => :user_role_relationships end class UserRoleRelationship < ActiveRecord::Base belongs_to :user belongs_to :role end…

モデルのコールバックを使う

元記事はこちら 翻訳 Bad Smell <% form_for @post do |f| %> <%= f.text_field :content %> <%= check_box_tag 'auto_tagging' %> <% end %> class PostsController < ApplicationController def create @post = Post.new(params[:post]) if params[:auto_t…

込みいった生成処理をファクトリメソッドに置き換える

元記事はこちら 翻訳 Bad Smell class InvoicesController < ApplicationController def create @invoice = Invoice.new(params[:invoice]) @invoice.address = current_user.address @invoice.phone = current_user.phone @invoice.vip = (@invoice.amount …

モデルのロジックをモデルに移動する

元記事はこちら 翻訳 Bad Smell class PostsController < ApplicationController def publish @post = Post.find(params[:id]) @post.update_attribute(:is_published, true) @post.approved_by = current_user if @post.created_at > Time.now - 7.days @po…

モデルに仮想的な属性を追加する

元記事はこちら 翻訳 Bad Smell <% form_for @user do |f| %> <%= text_field_tag :full_name %> <% end %> class UsersController < ApplicationController def create @user = User.new(params[:user]) @user.first_name = params([:full_name]).split(' '…

スコープを使ってアクセスする

元記事はこちら 翻訳 オブジェクトのオーナーとcurrent_userを比較することで、アクセス権をチェックしたいとおもったら、そんな冗長でイケてない書き方はせずに、スコープをつかてアクセスしましょう。 Bad Smell class PostsController < ApplicationContr…

Modelの関連付けを利用する

元記事はこちら 翻訳 Bad Smell class PostsController < ApplicationController def create @post = Post.new(params[:post]) @post.user_id = current_user.id @post.save end end この例では、user_idは明らかに@postに割り当てられます。大きな問題には…

検索処理をスコープに入れる

元記事はこちら 翻訳する BadSmell class PostsController < ApplicationController def index @published_posts = Post.find(:all, :conditions => { :state => 'published' }, :limit => 10, :order => 'created_at desc') @draft_posts = Post.find(:all,…

Rails Best Practiceを読む

転職してPHP->Ruby(Rails)に宗旨替えしました。 Railsの書き方にようやく慣れてきたものの、まだまだ書き方で指摘されることが多いので、 RailsのBestPracticeを読んで勉強することにしました。 1日1本目標に読んでいく。