【问题标题】:Rails 生成控制器命令不构建视图文件
【发布时间】:2022-01-23 03:13:48
【问题描述】:

我一直在努力理解为什么我无法获取为我的 Rails 项目创建的视图文件。文档显示生成控制器也会生成关联视图: Rails Docs

如果我使用相同的命令,我会生成一个文件,即控制器。 My command

我的 Rails 项目中 Views 文件夹中仅有的两个文件是 mailer.html.erb 和 mailer.text.erb

我做错了吗?我是否手动创建视图文件,如果是这样,我似乎无法将它们“连接”到关联的控制器。我是 Rails 的新手,所以任何见解都会有所帮助。谢谢!

【问题讨论】:

    标签: ruby-on-rails view controller


    【解决方案1】:

    试试这个命令:

    rails g controller Articles index create
    

    如果您在命令中输入控制器名称,您可以动态创建方法和视图。

    【讨论】:

    • 这个命令中的“create”这个词在做什么?
    • 与索引类似。如果您键入代码,则您在 Articles 控制器中创建了 index 和 create 方法。之后,Rails 在views 目录中创建articles/index.html.erb 和create.html.erb。
    【解决方案2】:

    您只在命令中创建了一个控制器,而不是任何方法,这就是不生成视图的原因。如果您需要为特定方法生成视图,则可以运行下面列出的命令。

    rails g控制器文章索引展示

    这里,index、show 是方法名。因此,此命令将创建 ArticlesController 以及相应的视图文件。

    【讨论】:

      【解决方案3】:

      您可以使用scaffold 选项。

      rails g scaffold Post name:string title:string content:text
      

      此命令将生成以下文件。

      File Purpose
      db/migrate/20100207214725_create_posts.rb Migration to create the posts table in your database (your name will include a different timestamp)
      app/models/post.rb The Post model
      test/unit/post_test.rb Unit testing harness for the posts model
      test/fixtures/posts.yml Sample posts for use in testing
      config/routes.rb Edited to include routing information for posts
      app/controllers/posts_controller.rb The Posts controller
      app/views/posts/index.html.erb A view to display an index of all posts
      app/views/posts/edit.html.erb A view to edit an existing post
      app/views/posts/show.html.erb A view to display a single post
      app/views/posts/new.html.erb A view to create a new post
      app/views/posts/_form.html.erb A partial to control the overall look and feel of the form used in edit and new views
      test/functional/posts_controller_test.rb Functional testing harness for the posts controller
      app/helpers/posts_helper.rb Helper functions to be used from the post views
      test/unit/helpers/posts_helper_test.rb Unit testing harness for the posts helper
      app/assets/javascripts/posts.js.coffee CoffeeScript for the posts controller
      app/assets/stylesheets/posts.css.scss Cascading style sheet for the posts controller
      app/assets/stylesheets/scaffolds.css.scss Cascading style sheet to make the scaffolded views look better

      【讨论】:

        猜你喜欢
        • 2014-08-22
        • 2011-06-18
        • 1970-01-01
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        • 1970-01-01
        相关资源
        最近更新 更多