Raiilsでスキャフォールドしてみる – まとめ。
前回までの作業をふまえて、
今回は、基本的なCRUDアプリをスキャフォールドしてみます。
作るのは、apple_typeとappleアプリ。
appleのapple_type_idはappleのidと多対一関係でつなげます。
公開ファイルは、前回と同じく、以下参照。
■github
https://github.com/dog-ears/demo_ror
■heroku
https://dog-ears-ror.herokuapp.com/
※以下アドレスからユーザー登録可能
https://dog-ears-ror.herokuapp.com/users/new
【aplle_typeの作成】
(1)scaffoldの実行
rails generate scaffold apple_type name:strin
app/assets/stylesheets/scaffolds.scss が conflict。
→ bootstrap関連でカスタム修正してるため。
→ 上書きしないで進む。
(2)migrationの実行
rake db:migrate
(3)モデルにヴァリデーションを記載する。
#/app/models/apple_type.rb validates :name, presence: true # 値が存在すれば検証成功
(4)bootstrapの適用
rails g bootstrap:themed Apple_types
以下、コンフリクト、全て「y」で。
/app/views/apple_types/index.html.erb
/app/views/apple_types/new.html.erb
/app/views/apple_types/edit.html.erb
/app/views/apple_types/_form.html.erb
/app/views/apple_types/show.html.erb
(5)検索と並び替えとページングを実装
・コントローラーの修正
#/app/controllers/apple_types_controller.rb def index @apple_types = AppleType.all end ↓ def index @q = AppleType.search(params[:q]) @apple_types = @q.result(distinct: true) end
・ビューの修正
git参照
【aplleの作成】
rails generate scaffold apple name:string apple_type_id:integer
(1)関連の作成
#/app/models/apple_type.rb has_many :apples
#/app/models/apple.rb belongs_to :apple_type
(2)migrationの実行
rake db:migrate
(4)bootstrapの適用
rails g bootstrap:themed Apples
(5)リレーション関連のビュー修正
リレーショナルカラムのinputは以下のように修正
#/app/views/apples/_form.html.erb <%= f.input :apple_type_id %> ↓ <%= f.association :apple_type, as: :select %>
#/app/views/apples/show.html.erb <dd><%= @apple.apple_type_id %></dd> ↓ <dd><%= @apple.apple_type.name %></dd>
#/app/views/apples/index.html.erb <%= @apple.apple_type_id %> ↓ <%= @apple.apple_type.name %>
(6)検索と並び替えとページングを実装
■kaminariをBootstrap3、Rails4.2環境で使う![Ruby 2.3]
http://morizyun.github.io/blog/kaminari-gem-paginator-rails/
以上で、2つのCRUDアプリとそのリレーションが設定できました。
Rails、すごいなぁ・・・。
しかし、laravelも負けてはないはず・・・!
ということで、次回からは、laravelのパッケージ開発をして、
Railsと同じように簡単にCRUDアプリ開発ができるようにしていこうと思います。
Discussion
New Comments
No comments yet. Be the first one!