Building Relationships Between Rails Models
Contributed by Brian Leonard, maintained by Gail Chappell
September 2007 [Revision number: V6.0-1]
This tutorial describes how to build relationships (one-to-one and one-to-many) between models in a NetBeans Ruby on Rails project.
Contents
|
|
![Content on this page applies to NetBeans IDE 6.0 Content on this page applies to NetBeans IDE 6.0](../../../images/articles/60/netbeans-stamp.gif) |
Creating the Comment Model
This tutorial enhances the RubyWeblog project by enabling readers to add comments to a blog post. You begin by creating the Comment model to store instances of readers' comments. The project already includes a Post model for storing instances of blog posts.
-
In the Projects window, expand the RubyWebLog node if it is not already expanded, right-click the Models node and choose Generate.
-
Type Comment
in the Arguments field and click OK.
The Rails Generator creates a model named Comment. This model includes the following files:
- app/models/comment.rb. A file that holds the methods for the Comment model. This file is opened in the editing area.
- test/unit/comment_test.rb. A unit test for checking the model.
- test/fixtures/comments.yml. A test fixture for populating the model.
- db/migrate/migrate/003_create_comments.rb. A migration file for altering the structure of the database. This file is versioned 003 as the project already has two migration files,
001_create_posts.rb
and 002_add_body.rb
, which create and modify the posts table.
Migrating the Database
Here you add information to the migration file so that each instance of a reader's comment has, in addition to the automatically created id column, the id of the parent post, a time of creation, and a text description.
-
In the Output window, click the link for the 003_create_comments.rb
file.
The file opens in the editing area.
-
Add the following code (shown in bold) to create_table
in the self.up
method:
Code Sample 1: self.up method |
class CreateComments < ActiveRecord::Migration def self.up create_table :comments do |t| t.column 'post_id', :integer t.column 'created_at', :datetime t.column 'comment', :text end end
def self.down drop_table :comments end end
|
This migration creates a comments table with four fields: id
, which contains an integer, post_id
, which contains an integer; created_at
, which stores the date and time; and comment
, which contains a text description.
- Choose File > Save All.
-
Right-click the RubyWebLog node and choose Migrate Database > To Current Version.
This action updates the the database to include the comments table. The Output window indicates when the migration is complete.
Defining a Relationship Between the Post and Comment Models
You now have two models in the application: the Post model, which creates a new blog post; and the Comment model, which adds a comment to a blog post. Here you define a relationship between the two models so that a comment is associated with a single post, and a post can contain multiple comments.
- Expand the Models node and open
post.rb
.
-
Add the has_many
association to post.rb
.
Code Sample 2: has_many association in post.rb |
class Post < ActiveRecord::Base has_many :comments end
|
The has_many
method indicates that the post can have have zero, one, or more comment records associated with it.
-
Open Models > comment.rb
and add the belongs_to
association.
Code Sample 3: belongs_to association in comment.rb |
class Comment < ActiveRecord::Base belongs_to :post end
|
The belongs_to
method indicates that a comment can be associated with only one post. By default, ActiveRecord uses the post_id
to associate a comment with the post that has a matching post.id.
Modifying the Controller Scaffolding
Next you work with the controller, blog_controller.rb
, which generates the scaffolding, or the basic interface for creating, reading, updating, and deleting entries in the blog post.
-
Double-click Controllers > blog_controller.rb to open the blog_controller.rb
file in the editing area.
The controller has all of the scaffold actions, including index
, list
, show
, new
, create
, edit
, update
and destroy
.
-
Modify the show
action to save the post_id to the flash.
Code Sample 4: show action |
def show @post = Post.find(params[:id]) flash[:post_id] = @post.id end
|
The code finds the post associated with the id
parameter passed in with the request. It then stores the id
in the flash for later use. The flash is similar to an HTTP session, but across a single request. When you put something in the flash, it is available for the next request, and then is gone (hence the name flash).
-
Scroll to the end of the blog_controller.rb
file and add the following post_comment
action before the final end
statement:
Code Sample 5: post_comment action |
def post_comment @comment = Comment.new( "post_id" => flash[:post_id], "created_at" => Time.now, "comment" => params[:comment]['comment'] ) if @comment.save flash[:notice] = 'Comment was successfully added.' redirect_to :action => 'show', :id => flash[:post_id] end end
|
The post_comment
action is called when the user clicks the Post button to submit a comment. The first block of code gets the post_id
from the flash (which is something like 1, 2, or so on) and uses it to find the blog post associated with that id
. The code then creates a new Comment object to be associated with that post_id
, also consisting of the time created and the actual comment. The Rails framework passes the submitted parameters from the page as a hash (params[:comment]), from which the code pulls out the comment parameter (params[:comment]['comment']).
Comment is an ActiveRecord class, so calling its save method saves the comment record to the database. The message is then put in the flash. The code calls the show
action, which loads the show.rhtml
page. This page reloads the post and all of its comments, including the new one.
Modifying the View to Display Comments
Here you edit the show.rhtml
file, which displays an individual blog entry.
- Expand Views > blog and open
show.rhtml
.
-
Add the following code at the end of show.rhtml
.
Code Sample 6: Code for show.rhtml |
Comments
<% form_tag :action => 'post_comment' do %>
Comment
<%= text_area 'comment', 'comment' %> <%= submit_tag "Post" %> <%end %>
|
This code produces a form that includes a a text input area for writing the comment, and a Submit button labeled Post, as shown in Figure 1. The post_comment
action is called when the form is submitted.
- Save your files and run the application. If there are no new posts, create a new one.
-
Click a Permalink to view the details of a blog entry. Try adding a comment in the text area, but note that the blog does not yet display comments when you click the Post button.
If your posting is successful, you see a message at the top of the view, as shown in the following figure. In the next steps you add code to collect and display the comments.
<!---->
Figure 1: View of Comment Model, But Without Comments
Displaying the Comments
The blog does not yet display the comments that a reader adds, so here you fix that problem.
-
In blog_controller.rb
, find the show
action and insert the following post_comments
instance variable to collect the comments:
Code Sample 7: Code for blog_controller.rb |
def show @post = Post.find(params[:id]) @post_comments = @post.comments.collect flash[:post_id] = @post.id end
|
-
Modify show.rhtml
by copying and pasting the contents of the following
tag to just after the
Comments
line.
Code Sample 8: Code for show.rhtml |
|
This code stylizes the comments, displays them in a bulleted list, and includes the date and time that the comment was posted.
-
Choose File > Save All, then refresh your browser.
The comments now appear in the blog in a bulleted list, as shown in the following figure.
<!---->
Figure 2: View of Comment Model, With Comments
分享到:
相关推荐
rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails 2.3.2离线安装rails ...
Rather than toss you into the middle of the framework’s Model-View-Controller architecture, as many books do, Learning Rails 5 begins with the foundations of the Web you already know. You’ll learn ...
rails常用命令,例如新建rails项目,新建controller、model 等等
简介 Ruby On Rails 框架自它提出之日...Rails 是一个真正彻底的 MVC(Model-View-Controller) 框架,Rails 清楚地将你的模型的代码与你的控制器的应用逻辑从 View 代码中分离出来。Rails 开发人员很少或者可能从未遇到
《Ruby on Rails Tutorial》中文版(原书第2版,涵盖 Rails 4) Ruby 是一门很美的计算机语言,其设计原则就是“让编程人员快乐”。David Heinemeier Hansson 就是看重了这一点,才在开发 Rails 框架时选择了 Ruby...
[Pragmatic Bookshelf] Crafting Rails Applications Expert Practices for Everyday Rails Development (E-Book) ☆ 图书概要:☆ Rails 3 is a huge step forward. You can now easily extend the framework, ...
Ruby on Rails Guides v2 - Ruby on Rails 4.2.5
一个用Ruby on Rails搭建的图片分享的网站项目.完整源代码
rails, Ruby on Rails 欢迎使用 RailsRails 是一个web应用程序框架,它包括根据 Model-View-Controller ( MVC ) Pattern 创建数据库备份的web应用程序所需的所有内容。理解 MVC Pattern 是理解 Rai
《Rails之道》按照Rails的各个子系统进行组织编排,分别介绍了Rails的环境、初始过程、配置和日志记录,Rails的分配器、控制器、页面生成和路由,REST、资源和Rails,ActiveRecord的基础、关联、验证和高级技巧,...
中文世界唯一一本Rails 4.0.0 + Ruby 2.0.0 的自學書籍
rails文档 rails api 英文
本资源是参照rails敏捷开发第四版书中的例子,rails的版本是rails3.2.6
adminlte-rails, AdminLTE Rails gem 将AdminLTE主题与 Rails 资产管道集成 AdminLTE Rails gem AdminLTE 是后端的高级 Bootstrap 主题。英镑 AdminLTE Rails gem 与 Rails 资产管道集成了英镑AdminLTE主题。安装将...
Bootstrap 3 和 Rails 4(样例用的是Ruby 2.1.1,Rails 4.1.4) Table of Contents Preface 1 Chapter 1: Introducing Web Application Development in Rails 7 Why Bootstrap with Rails? 8 Setting up a Todo ...
rails指南 中文版
第二部分和第三部分与 Rails紧密联系,着重对Ruby这门语言进行详细介绍;所采用的Rails应用示例,既说明了Ruby的特性,也给出了有关Rails的重要信息。第四部分讲述了如何应用第二部分和第三部分的Ruby知识来开发...
使用Aptana+Rails开发Rails Web应用 有Aptana的安装配置等等,中文
rails2-sample good book