`
haiyang
  • 浏览: 70332 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

建立rails model之间的关系

阅读更多

Building Relationships Between Rails Models

This tutorial describes how to build relationships (one-to-one and one-to-many) between models in a NetBeans Ruby on Rails project.

Contents

Tutorial Requirements
Creating the Sample Database
Creating the Comment Model
Migrating the Database
Defining a Relationship Between the Comment and Post Models
Modifying the Controller Scaffolding
Modifying the View to Display Comments
Displaying the Comments
  Content on this page applies to NetBeans IDE 6.0

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.
  1. In the Projects window, expand the RubyWebLog node if it is not already expanded, right-click the Models node and choose Generate.

  2. 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.
  1. In the Output window, click the link for the 003_create_comments.rb file.

    The file opens in the editing area.
  2. 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.
  3. Choose File > Save All.
  4. 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.
  1. Expand the Models node and open post.rb.
  2. 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.
  3. 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.
  1. 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.
  2. 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).
  3. 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.
  1. Expand Views > blog and open show.rhtml.
  2. 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.
  3. Save your files and run the application. If there are no new posts, create a new one.
  4. 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

    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.
  1. 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
  2. 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

        <% for comment in @post_comments %>
      • <%= comment.comment %>


        Posted on <%= comment.created_at.strftime("%B %d, %Y at %I:%M %p") %>


      • <% end %>


      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

      Figure 2:  View of Comment Model, With Comments
评论

相关推荐

    Rails 101S

    - **MVC架构与RESTful概念**:介绍模型(Model)、视图(View)、控制器(Controller)三者之间的关系以及RESTful API的设计原则。 - **深入解析Controller & Model**:进一步探讨Controller和Model的工作原理,理解如何...

    rails查询学习笔记

    4. **Associations**:Rails的关联功能允许模型之间建立联系,如`has_many`、`belongs_to`、`has_one`、`has_many :through`等,它们简化了多表操作。 5. **Count、Sum、Average等聚合函数**:Rails提供了计算记录...

    rails2-sample

    掌握Ruby语言是学习Ruby on Rails的前提条件,因为Rails正是建立在Ruby之上的。 #### 4. Rails Revealed(揭示Rails) 这部分内容会更进一步地探索Rails的内部机制,包括其架构、工作流程以及一些高级特性。例如,...

    ruby on rails(开发文档)

    Rails是建立在Ruby之上的,因此深入理解Ruby是学习Rails的基础。 2. **Rails架构**:了解MVC模式是至关重要的。Model负责数据模型和业务逻辑,View负责显示用户界面,Controller则作为两者之间的桥梁,处理用户请求...

    ruby on rails入门

    - **使用 Model 维护关联**:利用 ActiveRecord 的关联功能来处理表之间的关系。 - **Session 变量**:使用 Session 变量来保存用户的数据,以便在不同页面之间传递。 - **导航栏**:设计并实现应用的导航栏,提供...

    应用Rails进行敏捷Web开发

    2. **Rails框架结构**:Rails采用MVC架构,其中Model负责业务逻辑和数据处理,View负责显示用户界面,Controller处理用户请求并协调Model和View。理解这三个组件的职责以及它们之间的交互是学习Rails的基础。 3. **...

    ruby on rails入门基础

    Ruby on Rails,简称Rails,是基于Ruby语言的一个开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发更简洁、高效。Rails强调“约定优于配置”,大大减少了开发者在项目设置上的工作...

    ruby on rails学生选课系统

    在Rails中,我们可以利用ActiveRecord来定义这些模型,并通过关系(如has_many和belongs_to)来建立它们之间的关联。 接下来是视图(View)部分,它是用户与系统交互的界面。学生选课系统的视图应包含学生登录注册...

    Rails 3 in Action

    ### 关于《Rails 3 in Action》 #### 1. Ruby on Rails, the framework - **定义**: Ruby on Rails(简称Rails)是一个基于Ruby语言的Web应用开发框架。... - **定义多对一关联**: 在模型之间建立关联关系。

    ruby on rails中Model的关联详解

    ### Ruby on Rails 中 Model 关联详解 #### 前言 在进行模型关联的设计与实现时,有几个重要的原则需要遵循: 1. **关联关系需要在两端都定义**:只有当两个模型之间的关联关系被双方正确地定义后,才能正常工作...

    create todo list ruby on rails

    Ruby是一种动态的面向对象程序设计语言,而Rails则是建立在其之上的一套完整框架。 #### 三、准备工作 在开始开发之前,确保已经安装了以下组件: - **Ruby**: 版本建议为1.8.4或以上。 - **Rails**: 本文档所使用...

    [Web开发敏捷之道--应用rails源代码][5]txt

    2. **Rails架构**:了解MVC模式,包括模型(Model)负责数据处理,视图(View)负责展示,控制器(Controller)作为模型和视图之间的桥梁。 3. **Rails生成器**:学习如何使用Rails的生成器快速创建控制器、模型、...

    learn-rails:学习 Rails

    在 "learn-rails" 项目中,通过实际的 RailsApp 项目练习,你将有机会将这些理论知识付诸实践,逐步建立起对 Rails 的深入理解和熟练运用。这个过程中,你将遇到问题,解决问题,从而不断巩固和深化你的 Rails 技能...

    LinkMe:Rails 个人项目

    【LinkMe:Rails个人项目】是一个使用Ruby on Rails框架开发的个人项目,它可能是一个用于建立个人联系网络或社交平台的应用。在这个项目中,重点在于利用Rails的强大功能和灵活性来构建一个用户友好的Web应用程序。...

    sample_app:Ruby on Rails 教程示例应用程序

    8. **模型关联**:在 Ruby on Rails 中,模型之间可以建立关联,比如 `has_many`、`belongs_to` 等。这使得数据操作更加便捷,例如一个用户可以有多个文章,那么 `User` 模型中可以定义 `has_many :articles`。 9. ...

    rails_memo

    6. **ActiveRecord 关联(Associations)**:Rails 提供了多种关联类型,如 `has_many`、`belongs_to` 等,帮助我们在模型之间建立关系。例如,一个用户可能可以拥有多个笔记,这可以通过在 `User` 和 `Note` 模型间...

    rails-hello-world-app:我的第一个Rails应用程序!

    总的来说,通过这个"rails-hello-world-app",你可以开始学习Rails的基本概念,如路由、控制器、视图和MVC架构,并逐步建立起对Web开发的理解。继续探索,你会发现Rails不仅适合快速开发,而且有着丰富的社区资源和...

    rails_sample_app

    - **模型(Model)**:负责处理业务逻辑和数据存储,通常与数据库交互,如ActiveRecord对象。 - **视图(View)**:展示用户界面,与模型交互,将数据渲染成用户可见的形式。 - **控制器(Controller)**:作为模型...

    techmaster-rails

    4. **ActiveRecord**:了解Rails内置的ORM(对象关系映射),它是如何处理数据库操作的,包括创建模型、定义属性、建立关联和执行查询。 5. **视图模板(Views)**:学习使用ERB(Embedded Ruby)或其他模板引擎来...

    shop:使用Ruby On Rails购买回购

    在Rails应用中,这可以通过创建关联模型来实现,例如,产品和选项可以建立多对多关系,使用`has_and_belongs_to_many`或`has_many :through`关联。同时,删除产品选项需要考虑数据库中的数据完整性,可能需要用到软...

Global site tag (gtag.js) - Google Analytics