将新用户存储到另一个模型
Store new user to another model
我有一个书架模型,里面有数据。
bookshelf: id, book_id, user_id, is_read:false
而且我需要 pass/add 每个新用户 id
进入书架 user_id
因为所有存在 book_id
的
//user.rb
has_many :bookshelfs
has_many :books, through: :bookshelfs
//bookshelf.rb
belongs_to :user
belongs_to :book
我正在使用 gem。我需要在 regestrations_controller.rb?
里面写什么
def create
super
...
end
您可以在您的用户模型中添加 after_create
挂钩,这样,无论何时创建新用户,您都会将他添加到书架。
class User < ActiveRecord::Base
...
after_create :add_to_all_existing_books
...
private
def add_to_all_existing_books
Book.where(is_read: false).each do |b|
Bookshelf.create(book_id: b.id, user_id: self.id, is_read: false)
end
end
end
我有一个书架模型,里面有数据。
bookshelf: id, book_id, user_id, is_read:false
而且我需要 pass/add 每个新用户 id
进入书架 user_id
因为所有存在 book_id
的
//user.rb
has_many :bookshelfs
has_many :books, through: :bookshelfs
//bookshelf.rb
belongs_to :user
belongs_to :book
我正在使用 gem。我需要在 regestrations_controller.rb?
里面写什么def create
super
...
end
您可以在您的用户模型中添加 after_create
挂钩,这样,无论何时创建新用户,您都会将他添加到书架。
class User < ActiveRecord::Base
...
after_create :add_to_all_existing_books
...
private
def add_to_all_existing_books
Book.where(is_read: false).each do |b|
Bookshelf.create(book_id: b.id, user_id: self.id, is_read: false)
end
end
end