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.
zetetic
source share