Ruby Rails:向博客添加描述时遇到问题

Ruby on Rails: Having trouble adding a description to blog

在我的 Rails 应用程序中,所有 post 都显示在索引页面上。索引页上只显示 post 的标题和发布日期。例如,如果您单击 post,您将被带到 localhost:3000/posts/1,在那里您可以看到标题、日期、body 和 post 的评论。

我想做什么

我不想在索引页上显示每个 post 的标题和日期,我想显示每个 post 的标题、日期和简短描述。

我做了什么

new.html.erb是新建post的页面,部分内容如下:

<%= form_for :post, url: posts_path do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :body %>
<% end %>

所以我补充说:

<%= f.text_field :description %>

我的 post 模特:

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

所以,我补充说:

t.string :description

那没有用。所以我试着在终端

中这样做
$ rails g model Post title:string description:string body:text --force

那更糟。总的来说,我最终遇到了很多错误,我刚刚重新启动了教程。

所以,我的问题是:"How can I add a description to my posts?"

您可以通过 运行迁移来完成此操作。 运行rails generate migration add_description_to_posts description:string

然后运行rake db:migrate迁移到运行。然后您的帖子中将有一个描述列 table

然后将描述添加到 posts,您需要在 post 控制器的 posts 参数中添加 :description 并添加一个输入posts 表单中的描述字段。

要显示描述,您需要包含标签 <%= @post.description %>

您有两个选择:

选项 1:您不想创建 new migration file

step1: 你运行 rake db:rollback

step2:在你的 migration file 中添加 t.string :description

class CreatePosts < ActiveRecord::Migration
 def change
   create_table :posts do |t|
     t.string :title
     t.string :description
     t.text :body

     t.timestamps
   end
  end
end

step3: 你运行 rake db:migrate

step4:在你的new.html.erb中,你可以这样做:

<%= form_for :post, url: posts_path do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :description %>
  <%= f.text_area :body %>
<% end %>

选项 2: 您要创建 new migration file

第 1 步:您创建 new migration file 以将 new column 添加到 your table

rails generate migration add_description_to_posts description:string

step2: 在创建的迁移文件中,添加新列

add_column :posts, :description, :string

step3: 你运行 rake db:migrate

step4:在你的new.html.erb中,你可以这样做:

<%= form_for :post, url: posts_path do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :description %>
  <%= f.text_area :body %>
<% end %> 

请按照以下步骤操作:

步骤 1:Migration 使用 rails 生成器添加新字段。

rails g migration add_description_to_posts

第 2 步:在生成的迁移文件中:

class AddDescriptionsToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :description, :string        
  end
end

第 3 步:迁移数据库

rake db:migrate

步骤 4:Change 可见。

<%= form_for :post, url: posts_path do |f| %>
 <%= f.text_field :title %>
 <%= f.text_area :body %>
 <%= f.text_area :description %>
<% end %>

第五步:在PostController.rb中,在白名单参数中添加说明:

def post_params
  params.require(:post).permit(:title, :body, :description)
end

如果您遇到任何困难,请告诉我。