`
sillycat
  • 浏览: 2543417 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Rails Study(III)Creating a sample

阅读更多
Rails Study(III)Creating a sample

7. Adding a Second Model
7.1 Generating a Model
>rails generate model Comment commenter:string body:text post:references
class Comment < ActiveRecord::Base
  belongs_to :post
end

The model belongs_to
migrate database to mysql
>rake db:migrate

7.2. Associating Models
edit post.rb and add the other side of the association:
  has_many :comments
If you have an instance variable @post containing a post, you can retrieve all the comments belonging to that post
as the array @post.comments

7.3 Adding a Route for Comments
>vi routes.rb
Railsexample::Application.routes.draw do
  root :to => "home#index"
  resources :posts do
    resources :comments
  end
end  

7.4 Generating a Controller
>rails generate controller Comments

Link the comments pages to posts pages.
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %> 
<div class="field">    
<%= f.label :commenter %><br />    
<%= f.text_field :commenter %> 
</div>  
<div class="field">    
<%= f.label :body %><br />    
<%= f.text_area :body %> 
</div>  
<div class="actions">    
<%= f.submit %> 
</div>
<% end %>

Link the controller
  def create    
    @post = Post.find(params[:post_id])    
    @comment = @post.comments.create(params[:comment])    
    redirect_to post_path(@post)  
  end

show comments on the post page
<h2>Comments</h2>
<% @post.comments.each do |comment| %> 
<p>    
<b>Commenter:</b>    
<%= comment.commenter %> 
</p>    
<p>    
<b>Comment:</b>    
<%= comment.body %> 
</p>
<% end %>

It is done. Go to the URL http://localhost:3000/posts/2 to add comments.

8. Refactoring
8.1 Rendering Partial Collections
create the file app/views/comments/_comment.html.erb
<p>  
<b>Commenter:</b>  
<%= comment.commenter %>
</p>  
<p>  
<b>Comment:</b>  
<%= comment.body %>
</p>

change the file show.html.erb to >
<h2>Comments</h2>
<%= render :partial => "comments/comment",           
           :collection => @post.comments %>

8.2. Rendering a Partial Form
create a file app/views/comments/_form.html.erb
<%= form_for([@post, @post.comments.build]) do |f| %> 
<div class="field">    
<%= f.label :commenter %><br />    
<%= f.text_field :commenter %> 
</div>  
<div class="field">    
<%= f.label :body %><br />    
<%= f.text_area :body %> 
</div>  
<div class="actions">    
<%= f.submit %> 
</div>
<% end %>

edit the page show.html.erb>
<h2>Add a comment:</h2>
<%= render "comments/form" %>

9. Deleting Comments
in file /app/views/comments/_comment.html.erb
<p>  
<%= link_to 'Destroy Comment', [comment.post, comment],               
:confirm => 'Are you sure?',               
:method => :delete %>
</p>

add delete method in controller
  def destroy    
    @post = Post.find(params[:post_id])    
    @comment = @post.comments.find(params[:id])    
    @comment.destroy    
    redirect_to post_path(@post)  
  end

9.1 Deleting Associated Objects
change in app/models/post.rb
  has_many :comments, :dependent => :destroy

10. Security
Rails provides a very simple HTTP authentication system that will work nicely in this situation.
edit our controller app/controllers/application_controller.rb
  protect_from_forgery    
 
  private    
 
  def authenticate      
    authenticate_or_request_with_http_basic do |user_name, password|      
      user_name == 'admin' && password == 'password'  
    end
  end

I put put this method inside of ApplicationController so that it is available to all of our controllers.
In post controller
  before_filter :authenticate, :except => [:index, :show]

In comments controller
  before_filter :authenticate,nly => :destroy

11. Building a Multi-Model Form
Create a new model to hold the tags
>rails generate model tag name:string post:references
>rake db:migrate

edit the post.rb file to create the other side of the association. And to tell rails that you intend to edit tags via posts.
accepts_nested_attributes_for
has_many :tags
  accepts_nested_attributes_for :tags, :allow_destroy => :true,    
                                :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }

The :allow_destroy option on the nested attribute declaration tells Rails to display a "remove" checkbox on the view that you'll
build shortly.
The :reject_if option prvents saving new tags that do not have any attributes filled in.

modify views/posts/_form.html.erb to render a partial to make a tag:
<% @post.tags.build %>
<%= form_for(@post) do |post_form| %>
...snip...
<%= render :partial => 'tags/form',             
       :locals => {:form => post_form} %>
  <div class="field">
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </div>

create folder app/views/tags and a new file _form.html.erb
<%= form.fields_for :tags do |tag_form| %> 
<div class="field">    
<%= tag_form.label :name, 'Tag:' %>   
<%= tag_form.text_field :name %> 
</div>  
<% unless tag_form.object.nil? || tag_form.object.new_record? %>   
<div class="field">      
<%= tag_form.label :_destroy, 'Remove:' %>     
<%= tag_form.check_box :_destroy %>   
</div>  
<% end %>
<% end %>

edit app/views/posts/show.html.erb template to show our tags.
<p>  
<b>Tags:</b>  
<%= @post.tags.map { |t| t.name }.join(", ") %>
</p>

12 View Helper
Put all the reusable code for views.
edit app/helpers/posts_helper.rb
module PostsHelper  
  def join_tags(post)    
    post.tags.map { |t| t.name }.join(", ")  
  end
end

change show.html.erb from
<p>  
<b>Tags:</b>  
<%= @post.tags.map { |t| t.name }.join(", ") %>
</p>

to

<p>  
<b>Tags:</b>  
<%= join_tags(@post) %>
</p>

references:
http://guides.rubyonrails.org/getting_started.html

分享到:
评论

相关推荐

    rails2-sample

    从给定的文件信息来看,我们正在探讨的是一本关于Ruby on Rails的书籍,书名为《Simply Rails2》,作者是Patrick Lenz。本书旨在为初学者提供深入理解Ruby on Rails框架的指南,从基础概念到高级主题均有涵盖,是...

    Rails.Angular.Postgres.and.Bootstrap.2nd.Edition

    Rails is a great tool for building web applications, but it's not the best at everything. Embrace the features built into your database. Learn how to use front-end frameworks. Seize the power of the ...

    Agile Web Development with Rails 4

    You concentrate on creating the application, and Rails takes care of the details., Tens of thousands of developers have used this award-winning book to learn Rails. It’s a broad, far-reaching ...

    rails 5 test prescriptions build a healthy codebase

    Test the component parts of a Rails application, including the back-end model logic and the front-end display logic. With Rails examples, use testing to enable your code to respond better to future ...

    sample_app:“ Ruby on Rails教程”中的sample_app

    **Ruby on Rails 教程:sample_app 深度解析** `sample_app` 是一个基于 `Ruby on Rails` 框架的示例应用程序,它通常用于教学目的,帮助新手开发者理解 Rails 的基本概念和工作流程。在 `Ruby on Rails` 教程中,`...

    Ruby on Rails Tutorial Learn Rails by Example 的源代码

    这本书通过实际的示例项目“sample_app”引导读者深入理解Rails框架的各个方面。现在,我们来详细探讨这个源代码包中的知识点。 1. **Ruby on Rails框架基础**:Rails是一个基于Ruby语言的开源Web应用框架,遵循MVC...

    Rails101_by_rails4.0

    《Rails101_by_rails4.0》是一本专注于Rails 4.0.0版本和Ruby 2.0.0版本的自学教程书籍,它定位于中文读者,旨在成为学习Rails框架的参考教材。Rails(Ruby on Rails)是一个采用Ruby语言编写的开源Web应用框架,它...

    sample_app_4th_ed:Rails教程第4版“ sample_app”

    入门要开始使用该应用程序,请克隆存储库,然后安装所需的gem: $ cd /path/to/repos$ git clone https://bitbucket.org/railstutorial/sample_app_4th_ed.git sample_app_reference$ cd sample_app_reference$ ...

    Rails项目源代码

    Ruby on Rails,通常简称为Rails,是一个基于Ruby编程语言的开源Web应用框架,遵循MVC(Model-View-Controller)架构模式。这个“Rails项目源代码”是一个使用Rails构建的图片分享网站的完整源代码,它揭示了如何...

    flex 與 rails 開發的問題單管理sample

    本文将深入探讨“flex 與 rails 開發的問題單管理sample”这一主题,帮助读者理解如何结合这两种技术来创建一个高效的问题单管理系统。 Flex是一种基于Adobe AIR(Adobe Integrated Runtime)的开发框架,主要使用...

    [Rails] Crafting Rails Applications (英文版)

    Rails 3 is a huge step forward. You can now easily extend the framework, change its behavior, and replace whole components to bend it to your will, all without messy hacks. This pioneering book is the...

    关于rails 3.1 cucumber-rails 1.2.0

    Rails 3.1 和 Cucumber-Rails 1.2.0 是两个在Web开发领域非常重要的工具,尤其对于Ruby on Rails框架的测试和自动化流程。本文将深入探讨这两个组件,以及它们如何协同工作来增强软件开发的效率和质量。 首先,...

    Head First Rails A Learner's Companion to Ruby on Railsa.pdf

    《Head First Rails》是为学习Ruby on Rails的学习者提供的一个伴侣手册。本书是Head First系列的一部分,该系列书籍以其结合实际应用场景的教育方式而著称,旨在帮助读者快速掌握技能并迅速上手。《Head First ...

    Ruby on Rails Guides_ A Guide to Testing Rails Applications.pdf

    综上所述,《Ruby on Rails Guides_ A Guide to Testing Rails Applications.pdf》是一个全面的资源,无论你是Rails新手还是资深开发者,都能从中学习到如何为Rails应用编写高质量的测试。从理论到实践,从单元测试...

    Rails

    标题 "Rails" 指的是 Ruby on Rails,一个开源的Web应用程序框架,它基于Ruby编程语言,遵循MVC(模型-视图-控制器)架构模式。Rails由David Heinemeier Hansson在2004年创建,其设计理念是强调代码的简洁性、DRY...

Global site tag (gtag.js) - Google Analytics