Ruby on Railsで開発を行っていると
- この操作ってどうやるんだっけ?
- この機能を実装したいときはどのメソッドを使えばいいんだっけ?
- このエラー見たことあるけど、どうやって対応したんだっけ?
などと何度も同じことを調べてしまうことが多いので、自分の備忘録がてら、Railsの基本操作・トラブルシューティングについてまとめていこうと思います。
コマンド
プロジェクト作成
rails new hello_app
bundleスキップ
rails new app-name --skip-bundle
MySQLを使用して作成
rails new app-name --skip-bundle -d mysql
新規コントローラー作成
rails generate controller Users
※コントローラー名は複数形
複数単語の場合
rails generate controller UserCategories
※generateするときのコントローラー名はキャメルケース・スネークケースのどちらでも問題ないようです。
いずれで実行してもコントローラーファイル名はスネークケース、クラス名はキャメルケースに統一されます。
自分は統一した方が迷わず済むので、コントローラー・モデルともにキャメルクラスでコマンドを実行しています。
新規モデル作成
rails generate model User name:string email:string
※モデル名は複数形
複数単語の場合
rails generate model UserCategory name:string email:string
※複数単語命名についてはコントローラーと同様
コントローラー
各アクションの前に処理を実行
before_action :article_user_check
特定のアクションのみ
before_action :article_user_check, only: :show
複数
before_action :article_user_check, only: [:edit,:show,:update,:destroy]
特定のアクションを除外して実行
before_action :article_user_check, except: :show
複数
before_action :article_user_check, except: [:edit,:show,:update,:destroy]
データ作成
※ユーザーの新規記事(article)を作成
@article= current_user.articles.build(article_params) if @article.save flash[:success] = "記事を作成しました" redirect_to @article else render 'articles/new' end
ストロングパラメータ設定
private def article_params params.require(:article).permit(:title,:body) end
データ更新
@article= Article.find(params[:id]) if @article.update_attributes(article_params) flash[:success] = "記事を更新しました" redirect_to articles_url else render 'edit' end
モデル
1対多のリレーション
has_many :articles,dependent: :destroy
belongs_to :user
多対多のリレーション
※記事にカテゴリーを設定
has_many :categories, through: :article_categories has_many :article_categories, dependent: :destroy
has_many :articles, through: :article_categories has_many :article_categories, dependent: :destroy
belongs_to :article belongs_to :category
値が空であることを禁ずるバリデーション
validates :user_id,presence:true
値の文字数を制限するバリデーション
最大文字数
validates :title, length: { maximum: 30 }
最小文字数
validates :title, length: { minimun: 30 }
ビュー
新規登録画面
<%= form_for(@article) do |f| %> <%= f.label :title %> <%= f.text_field :title,placeholder:"記事の名称" %> <%= f.label :body %> <%= f.text_area :body,placeholder:"記事の本文" %> <%= f.submit "記事作成" %> <% end %>
リンク
<%= link_to “記事一覧”, articles_path %> <%= link_to articles_path do %> 記事一覧 <% end %>