ruby-on-rails 用户、文章和评论的嵌套种子循环

esyap4oy  于 2023-06-07  发布在  Ruby
关注(0)|答案(1)|浏览(172)

我播种一个本地论坛应用程序使用下面的。目的是:
1.创建10个用户
1.给予每个用户10篇文章
1.为每篇文章写10条评论,但从其他9个用户中随机选择
不确定是否将用户随机分配到评论。目前,它只是使用创建的第一个用户。我认为修复是在Comment.create! user_id: user部分,但不知道如何实现这一点。

seeds.rb

10.times do |user|
  User.create!(id: "#{user}", email: "user_email#{user}@email.com", password: 'password', created_at: Time.now, updated_at: Time.now, username: "#{user}_username", confirmed_at: Time.now)

  # Create 10 articles 
  10.times do |article|
    Article.create!(title: "Article #{article}", body: "Body
      - #{article} - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
      quis mauris turpis. Curabitur nec cursus lectus. In purus elit, bibendum in
      odio in, interdum porta neque. Nullam ultricies metus id lobortis interdum.
      Mauris volutpat nisl ac felis interdum ornare. Aenean interdum sollicitudin
      risus, et condimentum dolor molestie non. Integer lorem nisi, convallis non
      pulvinar quis, mollis suscipit sem. Phasellus luctus lacus id lobortis
      efficitur. Nam hendrerit tempus ante vel rhoncus. Phasellus vulputate odio non
      risus sodales interdum. Etiam vel bibendum erat. Proin sit amet velit eget leo
      vestibulum accumsan eu eget ligula. Vestibulum cursus ex tortor, eu semper leo
      maximus et. Sed turpis neque, sagittis vel mattis nec, tincidunt sit amet
      purus. Cras eget ullamcorper sem, sed ullamcorper mi. Donec in feugiat dolor.
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
      turpis egestas. Quisque non pharetra nulla. Nam libero lacus, interdum ac
      viverra ac, tempus ac lorem. In venenatis quis nulla quis pretium. Nam
      placerat, arcu a euismod dignissim, nisi orci bibendum neque, eget venenatis
      nisl sapien vel mi. Quisque quis nisl vitae mi faucibus dapibus eget ac ipsum.
      Aliquam vehicula dolor blandit volutpat efficitur. Nulla eu nunc purus.
      Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque iaculis
      venenatis tellus id pharetra. Phasellus at aliquam erat, id finibus est.",
      status: 'public', created_at: Time.now, updated_at: Time.now, user_id: user)
  end  
  10.times do |comment|
    comment = 1
    Comment.create!(body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
      quis mauris turpis. Curabitur nec cursus lectus. In purus elit, bibendum in
      odio in, interdum porta neque. Nullam ultricies metus id lobortis interdum.
      Mauris volutpat nisl ac felis interdum ornare. Aenean interdum sollicitudin
      risus, et condimentum dolor molestie non.", article_id: comment, user_id: user, created_at: Time.now, updated_at: Time.now)
  end
end

schema.rb

create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "status"
    t.integer "user_id", null: false
    t.integer "views", default: 0
    t.index ["user_id"], name: "index_articles_on_user_id"
  end

  create_table "comments", force: :cascade do |t|
    t.string "commenter"
    t.text "body"
    t.integer "article_id", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "status"
    t.integer "user_id", null: false
    t.index ["article_id"], name: "index_comments_on_article_id"
    t.index ["user_id"], name: "index_comments_on_user_id"
  end

create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.integer "role", default: 0
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "username"
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

article.rb

class Article < ApplicationRecord
  include Visible
  has_many :comments, dependent: :destroy
  belongs_to :user

  validates :title, presence: true, length: { minimum: 1, maximum: 40 }
  validates :body, presence: true, length: { minimum: 10, maximum: 10_000 }

  has_noticed_notifications model_name: 'Notification'
end

comment.rb

class Comment < ApplicationRecord
  # include Visible

  belongs_to :article
  belongs_to :user
  has_rich_text :body

  after_create_commit :notify_recipient
  before_destroy :cleanup_notifications
  has_noticed_notifications model_name: 'Notification'

  private

  # Provide the parameters using .with to use them
  # in the methods and callbacks in the instance,
  # The deliver_later takes advantage of ACTIVE JOB, which allows
  # emails to be sent outside of the request response cycle
  def notify_recipient
    CommentNotification.with(comment: self, article:).deliver_later(article.user)
  end

  def cleanup_notifications
    notifications_as_comment.destroy_all
  end
end

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable

  has_many :articles
  has_many :comments
  has_many :notifications, as: :recipient, dependent: :destroy

  def create
    # Create the user form params
    @user = User.new(user_params)
    if @user.save
      # Send the email
      UserNotifierMailer.send_signup_email(@user).deliver
      redirect_to(@user, notice: 'User created')
    else
      render action: 'new'
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :login)
  end

  # set user privileges within console using:
  # @user = User.first
  # @user.role = 1 # moderator
  # @user.save
  enum role: %i[user moderator admin]
  after_initialize :set_default_role, if: :new_record?

  def set_default_role
    self.role ||= :user
  end

  def self.ransackable_attributes(_auth_object = nil)
    ['username']
  end
end

已编辑****seeds.rb

def create_users(number)
  number.times.map{|i| User.create!(id: "#{i}", email: "user_email#{i}@email.com", password: 'password', created_at: Time.now, updated_at: Time.now, username: "#{i}_username", confirmed_at: Time.now)}
end

def create_articles_for_users(users, number)
  users.each do |user|
    number.times do |i|
      user.article.create!(title: "Article #{i}", body: "Body
      - #{i} - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
      quis mauris turpis. Curabitur nec cursus lectus. In purus elit, bibendum in
      odio in, interdum porta neque. Nullam ultricies metus id lobortis interdum.
      Mauris volutpat nisl ac felis interdum ornare. Aenean interdum sollicitudin
      risus, et condimentum dolor molestie non. Integer lorem nisi, convallis non
      pulvinar quis, mollis suscipit sem. Phasellus luctus lacus id lobortis
      efficitur. Nam hendrerit tempus ante vel rhoncus. Phasellus vulputate odio non
      risus sodales interdum. Etiam vel bibendum erat. Proin sit amet velit eget leo
      vestibulum accumsan eu eget ligula. Vestibulum cursus ex tortor, eu semper leo
      maximus et. Sed turpis neque, sagittis vel mattis nec, tincidunt sit amet
      purus. Cras eget ullamcorper sem, sed ullamcorper mi. Donec in feugiat dolor.
      Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
      turpis egestas. Quisque non pharetra nulla. Nam libero lacus, interdum ac
      viverra ac, tempus ac lorem. In venenatis quis nulla quis pretium. Nam
      placerat, arcu a euismod dignissim, nisi orci bibendum neque, eget venenatis
      nisl sapien vel mi. Quisque quis nisl vitae mi faucibus dapibus eget ac ipsum.
      Aliquam vehicula dolor blandit volutpat efficitur. Nulla eu nunc purus.
      Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque iaculis
      venenatis tellus id pharetra. Phasellus at aliquam erat, id finibus est.",
      status: 'public', created_at: Time.now, updated_at: Time.now, user_id: i)
    end
  end
end

def create_comments_for_articles(articles, users, number)
   articles.each do |article|
    comment_users = users.reject{|user| user == article.user}
    number.times do |i|
      article.comments.create!(user: comment_users.first, body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
      quis mauris turpis. Curabitur nec cursus lectus. In purus elit, bibendum in
      odio in, interdum porta neque. Nullam ultricies metus id lobortis interdum.
      Mauris volutpat nisl ac felis interdum ornare. Aenean interdum sollicitudin
      risus, et condimentum dolor molestie non.", article_id: i, created_at: Time.now, updated_at: Time.now)
    end
  end
end

def setup
  new_users = create_users(10)
  new_articles = create_articles_for_users(new_users, 5)
  new_comments = create_comments_for_articles(new_articles, new_users, 10)
end

setup

我认为问题出在create_articles_for_users中-当在new_articles变量上使用puts时,它显示了一个User对象

#<User:0x0000000105afc778>
#<User:0x00000001062da148>
#<User:0x00000001062935e0>
#<User:0x00000001061dca98>
#<User:0x0000000106016060>
#<User:0x0000000105e7ec48>
#<User:0x00000001060de240>
#<User:0x00000001063776c8>
#<User:0x00000001065b0b60>
#<User:0x000000010663a158>

comment_users = users.reject{|user| user[:id] == article.user}更改为comment_users = users.reject{|user| user[:id] == article[:id]}我在create_comments_for_articles '中获得了rails aborted! ActiveRecord::RecordInvalid: Validation failed: Article must exist /Users/lucas.shaw/rails_odin_project/db/seeds.rb:81:in`块(2个级别)

5sxhfpxr

5sxhfpxr1#

强烈建议:永远不要只写脚本代码。总是假设你以后会用到它的一部分--特别是因为实际上结构化的东西几乎是免费的。

def create_users(number)
  number.times.map{|i| User.create!(...)}
end

def create_articles_for_users(users, number)
  users.map do |user|
    number.times.map do |i|
      user.articles.create!(...)
    end
  end
end

def create_comments_for_articles(articles, users, number)
  articles.map do |article|
    comment_users = users.reject{|user| user == article.user}
    number.times.map do |i|
      article.comments.create!(user: comment_users.shuffle.first, ...)
    end
  end
end

def setup
  new_users = create_users(10)
  new_articles = create_articles_for_users(new_users, 1).flatten
  new_comments = create_comments_for_articles(new_articles, new_users, 10)
end

相关问题