LoginSignup
44
41

More than 5 years have passed since last update.

モデルだけネームスペースをつけずにscaffoldを生成する

Last updated at Posted at 2015-11-02

管理画面などを自分で作る場合、admin/blogs_controller.rbのようなネームスペースのついたコントローラーと、blog のようなネームスペースなしのモデルにアクセスするscaffoldを作りたくなります

ありがちな手順は、
rails generate scaffold blog
のようにネームスペースなしでscaffoldを生成したあとで、controllerやviewのファイルを移動して、さらにそれらのファイルがネームスペースなしのモデルを参照するように直していく、というものです

ですが、rails4に搭載されているscaffold_controller generatorを使うと、そんな面倒なことをしなくても最初から適切なscaffoldを生成させることができます

scaffold_controller

$ rails generate scaffold_controller --help
Usage:
  rails generate scaffold_controller NAME [field:type field:type] 
(中略)
Description:
    Stubs out a scaffolded controller, its seven RESTful actions and related
    views. Pass the model name, either CamelCased or under_scored. The
    controller name is retrieved as a pluralized version of the model name.
(私訳)
7つのRESTful actionと関連するViewを持ったscaffold controllerを生成します。CamelCaseまたはunder_scoredの形でモデル名を渡す事ができます。
controllerの名前は、モデル名に対してpluralized(複数形)されたものが使われます。

簡単に言うと、既存のmodelがあるときにそれ以外の部分を作ってくれるscaffold generatorです

具体的な手順

 たとえばblogという名前のモデルと、それを参照するadmin/blogs_contoller scaffoldを生成してみます

modelを生成

$ rails generate model Blog title:string status:integer:index content:text
      invoke  active_record
      create    db/migrate/20151102131211_create_blogs.rb
      create    app/models/blog.rb
      invoke    rspec
      create      spec/models/blog_spec.rb
      invoke      factory_girl
      create        spec/factories/blogs.rb

scaffoldを生成

$ rails generate scaffold_controller admin/blogs --model-name=blog
      create  app/controllers/admin/blogs_controller.rb
      invoke  haml
      create    app/views/admin/blogs
      create    app/views/admin/blogs/index.html.haml
      create    app/views/admin/blogs/edit.html.haml
      create    app/views/admin/blogs/show.html.haml
      create    app/views/admin/blogs/new.html.haml
      create    app/views/admin/blogs/_form.html.haml
      invoke  rspec
      create    spec/controllers/admin/blogs_controller_spec.rb
      create    spec/routing/admin/blogs_routing_spec.rb
      invoke    rspec
      create      spec/requests/admin/admin_blogs_spec.rb

生成されたadmin/blogs_controllerを見ると、ちゃんとネームスペースなしのBlogを参照するように作られています。やったね!

class Admin::BlogsController < ApplicationController
  before_action :set_blog, only: [:show, :edit, :update, :destroy]

  # GET /blogs
  # GET /blogs.json
  def index
    @blogs = Blog.all
  end
44
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
41