整合Rack、Sinatra、Rails与MongoDB的实践指南
1. 作者管理方法
在开发过程中,我们会涉及到作者管理的相关方法,如 new 和 create 方法。以下是具体代码:
# GET /authors/new
def new
@author = Author.new
@author.build_address
@author.books.build
end
# POST /authors
def create
@author = Author.new(params[:author])
@author.save!
redirect_to authors_path, notice: "Author created successfully"
rescue
render :new
end
new 方法用于初始化一个新的作者对象,并构建相关联的地址和书籍对象。这里需要注意的是,在对象创建时,并不意味着它已经被保存到数据库中。当在 create 方法中调用 @author.save! 时,对象才会被持久化到数据库。
关于 build_address 和 books.build 的区别,由于 Author 模型与 address 是
Web应用开发:Rack、Sinatra、Rails与MongoDB整合
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



