Rails 3, how to add a related post after creating the primary post (Books, Auto Add BookCharacter)

Rails newbie ... trying to figure out the right way to do something ...

In my application, users can create a book (I have this job)

What I want to do is when the user creates the book, the record is added to the BookCharacters table, something like (id, book.id, user.id, characterdescription.string.)

When a book is created, the user who created it should automatically be added as the first BookCharacter. After that, the user can manually add / edit any number of BookCharacters characters at his discretion. But first, I want them to add automatically by default.

So, in my book controller, I have:

def create @book = Book.new(params[:book]) respond_to do |format| if @book.save .... 

With Rails, is it the practice of adding such logic after saving the book? Something like

 Book.create( :creator => current_user.id) 

I appreciate the help

+6
ruby-on-rails ruby-on-rails-3
source share
2 answers

Understanding is the convention by which Rails implements relationships using ActiveRecord. The book has many characters, and each character belongs to the book, therefore:

 class Book < ActiveRecordBase has_many :characters end class Character < ActiveRecordBase belongs_to :book end 

Rails now assumes that the characters table will have a foreign key named book_id , which refers to the books table. To create a character in a book:

 @book = Book.new(:name=>"Book name") @character = @book.characters.build(:name=>"Character name") 

Now that @book saved (assuming both @book and @character valid), the row will be created in both the books and characters tables, with the character string linked via book_id .

To show that the character also belongs to the user, you can add this relation to the character model:

 class Character < ActiveRecordBase belongs_to :book belongs_to :user end 

Thus, Rails now expects characters also have a foreign key called user_id that points to the users table (which also needs the User model). To specify a user when creating a character:

 @book = Book.new(:name=>"Book name") @character = @book.characters.build(:name=>"Character name",:user=>current_user) 

You can also assign a foreign key by calling the appropriate method on the object:

 @character.user = current_user 

This all works because it follows the Rails conventions for naming models and tables. You can opt out of these conventions, but you will study Rails diligently.

+16
source share

I prefer something like (if User has_many Book):

 def create @book = current_user.books.new(params[:book]) respond_to do |format| if @book.save … 
0
source share

All Articles