Is there a way to scaffold a singleton resource in

2019-02-21 16:35发布

问题:

The regular way of scaffolding doesn't work if you are working with a singular resource, is there any way to get default singular controllers through scaffolding? Say if a user has only one post is there an easy was to run a command like:

rails g scaffold post -singular

回答1:

When you look at the scaffold options in Rails 3.1.1, you will see the following:

Usage:
  rails generate scaffold NAME [field:type field:type] [options]

Options:
  ...

ActiveRecord options:
  ...

Rspec options:
  [--singleton]                 # Supply to create a singleton controller

The output of rails g scaffold Post name:string body:text --singleton is

  invoke  active_record
  create    db/migrate/20111103072825_create_posts.rb
  create    app/models/post.rb
  invoke    rspec
  create      spec/models/post_spec.rb
   route  resources :posts
  invoke  scaffold_controller
  create    app/controllers/posts_controller.rb
  invoke    haml
  create      app/views/posts
  create      app/views/posts/index.html.haml
  create      app/views/posts/edit.html.haml
  create      app/views/posts/show.html.haml
  create      app/views/posts/new.html.haml
  create      app/views/posts/_form.html.haml
  invoke    rspec
  create      spec/controllers/posts_controller_spec.rb
  create      spec/views/posts/edit.html.haml_spec.rb
  create      spec/views/posts/new.html.haml_spec.rb
  create      spec/views/posts/show.html.haml_spec.rb
  invoke      helper
  create        spec/helpers/posts_helper_spec.rb
  create      spec/routing/posts_routing_spec.rb
  invoke      rspec
  create        spec/requests/posts_spec.rb
  invoke    helper
  create      app/helpers/posts_helper.rb
  invoke      rspec
  invoke  assets
  invoke    coffee
  create      app/assets/javascripts/posts.js.coffee
  invoke    scss
  create      app/assets/stylesheets/posts.css.scss
  invoke  scss
identical    app/assets/stylesheets/scaffolds.css.scss

So it seems that the scaffolding generates the usual view templates.

In Rails 3.0 this was an option for the whole generator, not only the one for Rspec. See the Railscast 216 for Generators in Rails 3. Perhaps you will find a generator in Rails 3.0.x that will fulfill your needs.



回答2:

I agree with this so I created a Github issue. Follow this if it helps. However I found the only way to fix this is to manually fix the problem. That means change the names by hand. I know you don't want to do that but I found some times that is the only way.