再会。
我的数据库(PostgeSQL)中有 2 个表:“用户”和“文件夹”。文件夹是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
谢谢你的帮助!