Adding to multiple tables in rails

I am sure this is a relatively simple question and there should be a good reasonable rail, but I'm not sure what it is.

Basically, I add books to the database, and I want to save the Author in a separate table. Therefore, I have a table called authors, which is referenced by table books.

I want to create a rails form for adding a book, and I would like it to be a simple form for Author, Title, Publisher, etc., and if she finds the author already in the authors table, then he should just refer to this entry, and if it is not in the authors table, she must add a new entry and refer to it.

I am sure there is an easy way to do this on rails - but I cannot find it.

Greetings

Robin

+4
source share
4 answers

I suggest you look at the Integrated Forms of Railscasts here .

+5
source

Assuming your form passes the name author_name and a hash of the book with the attributes of the book, you can do the following in your controller:

@author = Author.find_or_create_by_name(params[:author_name]) @book = Book.new(params[:book]) @book.author = @author @book.save 

This will find the author by this name or create him, and then assign this author to the created book.

Note. It also suggests that authors can be uniquely identified by their name, and this is usually not the case. For example, there may be a few guys called "Stephen King", and only one of them wrote The Shining

+6
source

robintw comment on Miki's answer:

It looks like a good way to do it - although I'm somewhat surprised that Rails doesn't do it any more automatically

These are four lines! What more can Rails do automatically? This is a wireframe, not a person. :)

And here it is in two versions:

 @author = Author.find_or_create_by_name(params[:author_name]) @book = Book.create params[:book].merge({:author_id => @author.id}) 

And Honza's answer has many virtues:

 class Book < ActiveRecord::Base ... def author_name=(author_name) self.author = Author.find_or_create_by_name author_name end end 

In this example, and provided that your form has a parameter such as "book [author_name]", your code is simple:

 @book = Book.create params[:book] 

Wowzers.

+1
source

Ultimately, it will be automatic (as per this post in Rails 2.2): http://ryandaigle.com/articles/2008/7/19/what-s-new-in-edge-rails-nested-models

0
source

All Articles