Ruby on Rails Developers Forum

For all Ruby on Rails (RoR) Expert Developers Programmers Coders
Ruby on Rails PHP .Net Developers Community, Nyros Technologies, Kakinada
 
Log in  or IF not a member please REGISTER
Username:
Password:   


Keyword
Log in | Profile 

Using belongs_to and has_many relations in rails app

 
Post new topic   Reply to topic    Ruby on Rails Developers Forum Index -> A little Ruby programming (Basic programming in RoR)
View previous topic :: View next topic  
Author Message
vijayalakshmi



Joined: 27 Nov 2009
Posts: 38

PostPosted: Wed Jun 30, 2010 10:01 am    Post subject: Using belongs_to and has_many relations in rails app Reply with quote

Hi friends,
Lets us have a brief introduction about belongs_to and has_many, before using them in rails application.
belongs_to:
~~~~~~~~~~
belongs_to is an association that sets up a one-to-one connection with
another model. So, each instance of the declaring model “belongs to”
one instance of the other model.
has_many:
~~~~~~~~~~
has_many association sets up a one-to-many connection with another
model. This indicates that each instance of the model has zero or more
instances of another model. In-short we can say has_many association
on the “other side” of a belongs_to association.

Now, implement these relations in a sample rails application.
Let us consider two models Book and Comment where a book may
contain any no.of comments and each comment belongs to one book.

Create a rails application, and generate two models named 'book' and 'comment' and follow the following files.

app/model/book.rb
~~~~~~~~~~~~~~~~~
class Book < ActiveRecord::Base
has_many :comments
end
app/models/comment.rb
~~~~~~~~~~~~~~~~~~~~~
class Comment < ActiveRecord::Base
belongs_to :book
end

And our migration files should be:
20....._create_books.rb
~~~~~~~~~~~~~~~~~~
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :title
t.text :description
t.timestamps
end
end
def self.down
drop_table :books
end
end
20..._create_comments.rb
~~~~~~~~~~~~~~~~~~~~~~~
class CreateComments < ActiveRecord::Migration
def self.up
create_table :comments do |t|
t.text :text
t.string :author
t.belongs_to :book
t.timestamps
end
end
def self.down
drop_table :comments
end
end
Now create controllers for books and comments,
app/controllers/comments_controller.rb
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class CommentsController < ApplicationController
def create
book = Book.find params[:book_id]
comment = book.comments.new params[:comment]
comment.save
flash[:notice] = 'Comment saved'
redirect_to book_path(book)
end
end
app/controllers/books_controllers.rb
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class BooksController < ApplicationController
def index
@books = Book.paginate :page => params[:page], :per_page => 3
end
def show @book = Book.find(params[:id])
@comments = @book.comments
end
def new
@book = Book.new
end
def edit
@book = Book.find(params[:id])
end
def create
@book = Book.new params[:book]
if @book.save
flash[:notice] = "#{@book.title} saved."
redirect_to @book
else
render :new
end
end
def update
@book = Book.find params[:id]
if @book.update_attributes(params[:book])
flash[:notice] = "#{@book.title} saved."
redirect_to @book
else
render :edit
end
end
def destroy
book = Book.find params[:id]
book.destroy
flash[:notice] = "#{book.title} deleted."
redirect_to books_path
end
end
And here comes to our views folder,
app/views/books/new.html.erb
~~~~~~~~~~~~~~~~~~~~~
<h1>New book</h1>
<% form_for(@book) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description, "rows"=>10,"cols"=>50 %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', books_path %>

app/views/books/show.html.erb:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<h1><%=@book.title%></h1>
<%= simple_format @book.description %>
<% if @comments %>
<h3>Comments:</h3>
<% for comment in @comments do %>
<p><strong><%=h(comment.author) %></strong>:</p>
<%= simple_format comment.text %>
<% end %>
<% end %>
<h3>Post Your Comment</h3>
<% form_for([@book, Comment.new]) do |form| %>
<p>Your name:</p>
<p><%= form.text_field :author %></p>
<p><%= form.label :text, 'Comment' %></p>
<p><%= form.text_area :text ,"rows"=>8,"cols"=>45%></p>
<%= form.submit 'Save' %>
<% end %>
<p>
<%= link_to 'Back', books_path %>
<%= link_to 'Edit', edit_book_path(@book) %> |
<%= link_to 'Delete', book_path(@book), :method => :delete, :confirm =>

"Are you sure?" %>
</p>

And make sure that config/routes.rb containing the following code:
config/ routes.rb
~~~~~~~~~~~~
map.resources :books do |book|
book.resources :comments, :only => :create
end
map.root :controller => 'books', :action => 'index'

You Can start the server and view our application,
http://localhost:3001

Thanks,
Vijayalakshmi.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Ruby on Rails Developers Forum Index -> A little Ruby programming (Basic programming in RoR)
Page 1 of 1

 latest topics 
 Topics   Replies   Author   Views   Last Post 
No new posts PROBLEMS CREATING AN SSH TUNNEL
0 clem_c_rock 7396 Tue May 07, 2013 6:18 pm
clem_c_rock View latest post
No new posts Module Control
0 mpiaser 750 Sun May 05, 2013 4:12 am
mpiaser View latest post
No new posts Difficulty in learning ruby and rails
8 moneysharma 5853 Sat Apr 20, 2013 6:37 am
lucyming View latest post
No new posts Implementing SEO in rails
1 Rohini Pamarty 3078 Sat Apr 20, 2013 6:36 am
lucyming View latest post
No new posts RVM installation on ubuntu 10.04 version.
2 konduri subrahmanyam 3966 Sat Apr 20, 2013 6:35 am
lucyming View latest post
No new posts How to connect to remote databases in Ruby ?
1 ranjit_nyros 2727 Tue Apr 16, 2013 7:50 am
liveproject101 View latest post
No new posts Install Safari & IE in Ubuntu
2 Anu Krishna 3500 Thu Apr 04, 2013 6:52 am
chrisluger2012 View latest post
No new posts Saving the files in a zip folder using "rubyzip"
0 ranjit_nyros 5409 Thu Mar 14, 2013 5:23 pm
ranjit_nyros View latest post
No new posts [SOLVED]: A must after the installation of phpmyadmin
0 ranjit_nyros 1463 Thu Mar 14, 2013 4:52 pm
ranjit_nyros View latest post
No new posts Cropping Images with Carrierwave + rmagick
0 ranjit_nyros 1433 Thu Mar 14, 2013 4:37 pm
ranjit_nyros View latest post




Hire an expert Ruby on Rails developer / coder / programmer or development team from India now!!

Other Forums : PHP   ::   .Net   |   Free unlimited HTML CSS templates download

Nyros Technologies   |   Kakinada City Portal   |   Developers Blog   |   About Ruby on Rails Experts   |   More