One to one relation in rails


Refer above figure books and cover_images tables

assumes that same image is never used on two different covers. there is always a one-to-one relationship between books and cover images.

For this rails requires  a foreign key.Foreign key goes to the table that represents the zero or one side of relationship. that’s mean with the less dominant table. here cover_images

while code

1) Foreign keys in Rails should be named with singular name of the referenced table followed by id. so  book_id

2) In Book model want to mention as follows

class Book < ActiveRecord::Base
has_one :cover_image
end

and we can access CoverImage as follows

@books = Book.all
<% @books.each do |book| %>
<%= book.cover_image.cover_image_path %>
<% end %>

2) In CoverImage model want to mention as follows

class CoverImage < ActiveRecord::Base
belongs_to :book
end

and we can access Book as follows

@cover_images = CoverImage.all

<% @cover_images.each do |cover_image| %>
<%= cover_image.book.name %>
<% end %>

www.klairvoyant.in

Advertisements
This entry was posted in rails, ROR, ruby on rails, web development and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s