通过前几天的例子,我们建立了自己的第一个blog网站,并实现了对数据库的CRUD操作,初步了解了Rails的MVC架构,使用rails generate model命令生成model文件,并执行rails db:migrate命令在数据库中创建相应的表;使用generate controller命令生成controller文件,在controller文件中编写业务流的控制程序,同时为了给用户一个直观的展示,我们需要编写一些views。Rails内置了一些路由,目前我们暂时不需要自己手动编写,使用rails默认的路由就可以实现想要的这些功能了。
前面我们是以article为对象,完整的学习了对其新建、变更、删除等的各种操作。那么怎么对已经发表的博客文章进行评论呢?今天我们就一起来学习一下。
首先,我们还是使用rails generate model命令来创建一个关于评论的model:
|
让我们来看一下自动生成的model文件(app/models/comment.rb
),
|
发现,这与之前生成的Article的model文件稍微有些区别,就是多了一个belongs_to语句,这是因为我们在执行命令的时候使用了article:reference参数,它的作用是在生成comment这个表的时候多了一列用来存放article id,时article和comment这两个表关联起来 。
然后,我们执行rails db:migrate命令,我们发现虽然在blog/db/migrate的路径下面除了我们这次生成的文件之外,也包括前几天我们生成的article相关的文件,但是在执行命令的时候,rails还是很聪明地只创建了comment这个表,因为article表已经存在了。
现在,让我们讲article和comment两个model进行关联,对象与对象的关系可以是一对一,可以是一对多,也可以是多对多。而博客的文章与评论的关系应该是一对多的关系,我们在comment.rb文件中已经知道comment belongs_to :article;那么在article.rb文件中如何来表示呢,我们使用语句has_many :comments。修改后的article.rb文件如下:
|
这样我们就建立了article与comment之间的关系,假如我们使用一个实例变量@article表示一个文章,那么就可以使用@article.comments来表示关于这篇文章的所有评论了。
给article添加路由的时候,我们是在blog/config/routes.rb文件中添加了这么一句代码:
resources :articles
由于comment与article的特殊关系,我们只需要把routes.rb文件变更如下便可以指定comment的路由了。
|
上述操作完成之后,让我们来生成comment相关的controller,执行rails generate controller命令:
|
我们需要在展示article的页面中加入comment相关的内容,现在让我们讲前几天编写的有关article的show.html.erb这个view修改如下:
|
当然,不要忘记在comment的controller中添加create方法,
|
启动服务后程序执行如下:
点击按钮之后页面: