种子 - 如何重新初始化我的种子 - 铁轨

时间:2016-01-20 22:57:30

标签: ruby-on-rails ruby

嗨,我创建了这个种子

rails = Course.create(title: "Ruby On Rails")
models = rails.chapters.create(title: "Models")

models.items << Lesson.create(title: "What is Active Record?", content: "Lesson content here")

models.items << Exercice.create(title: "The Active Record pattern", content: "Exo about active record pattern")
models.items << Exercice.create(title: "Object Relational Mapping", content: "Exo about ORM")
models.items << Exercice.create(title: "Active Record as an ORM Framework", content: "Exo about ORM")

models.items << Lesson.create(title: "Convention over Configuration in Active Record", content: "Lesson content here")

models.items << Exercice.create(title: "Naming Conventions", content: "Exo about naming convention")
models.items << Exercice.create(title: "Schema Conventions", content: "Exo about schema convention")

models.items << Lesson.create(title: "Model summary", content: "Lesson content here")

models.items << Exam.create(title: "Rails Models exam", content: "Exam content here")

puts "done"

我做过rake db:seed

我的控制器课程是:

class CoursesController&lt; ApplicationController中

  def index
    @courses = Course.all
  end

  def show
    @course = Course.find(params[:id])
  end

end

我的控制器章节是:

class ChaptersController&lt; ApplicationController中

  def show
    @course = Course.find(params[:course_id])
    @chapter = @course.chapters.find(params[:id])
  end

end

我的控制器章节是:

class ItemsController < ApplicationController

  def show
    @course = Course.find(params[:course_id])
    @chapter = @course.chapters.find(params[:chapter_id])
    @item = @chapter.items.find(params[:id])
  end
end

在app / views / courses / index.html.erb

<div class="container-page">
  <div class="padding-page">
    <div class="container-fluid">
      <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
          <div class="page-progress">
            <h1>
              Page en cours de réalisation
            </h1>

            <% @courses.each do |course| %>
            <h2>
            <%= link_to course.title, course %>

            </h2>
            <% end %>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>

但它很多次出现了标题课程,我想看到一次。如何重置或销毁或隐藏其他名称相同且具有相同结构的课程?

Here is the index iteration

如果您想了解更多信息,我会告诉您该怎么做。谢谢。

1 个答案:

答案 0 :(得分:1)

您多次运行rake db:seed了吗?如果是这种情况,请再次删除,创建,迁移,播种数据库。

如果将来您需要更新种子并重新运行它们,请确保不创建多个记录。您可以通过以下方式更改代码来实现:

rails = Course.create(title: "Ruby On Rails")
models = rails.chapters.create(title: "Models")

models.items << Lesson.create(title: "What is Active Record?", content: "Lesson content here")

到那个:

rails = Course.where(title: "Ruby On Rails").first_or_create
models = rails.chapters.where(title: "Models").first_or_create

models.items << Lesson.where(title: "What is Active Record?").first_or_create(title: "What is Active Record?", content: "Lesson content here")

查找表格中的第一个实例。如果无,则创建一个。