创建用户时在其他表中创建数据

时间:2013-04-21 18:21:35

标签: ruby-on-rails

美好的一天。

我的数据库中有2个表(PostgeSQL):“用户”和“文件夹”。文件夹为belongs_to :user,用户为has_many :folders。我需要用户,在创建帐户时会自动使用name: "Default", id: 1, user_id: current_user.id在文件夹表中创建一个文件夹。据我理解,我需要在create

中修改users_controller方法

这是我的user.rb

# == Schema Information
#
# Table name: users
#
#  id              :integer          not null, primary key
#  name            :string(255)
#  email           :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  password_digest :string(255)
#  remember_token  :string(255)
#  admin           :boolean          default(FALSE)
#

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  has_secure_password
  has_many :folders, dependent: :destroy

  before_save { email.downcase! }
  before_save :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }
  validates :password_confirmation, presence: true

  private

  def create_remember_token
    self.remember_token = SecureRandom.urlsafe_base64
  end
end

这是folder.rb

# == Schema Information
#
# Table name: folders
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  user_id    :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Folder < ActiveRecord::Base
  attr_accessible :name
  belongs_to :user
  has_many :bookmarks, dependent: :destroy

  validates :user_id, presence: true
  validates :name, presence: true
end

这是create

中的users_controller.rb方法
def create
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      redirect_to @user
      flash[:success] = "Welcome to Timio Bookmarks!"
    else
      if signed_in?
        redirect_to root_path
      else
        render 'new'
      end
    end
  end

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尝试类似:

@user.folders << Folder.new

在@ user.save

上进行保存之前