Reputation: 162
I searched around the SOF and couldn't find a simple answer for my simple question.
I have two classes, Author
and Book
.
class Author < ActiveRecord::Base
def greet
puts "Hello, I'm #{name}."
end
def describe
puts "That Author's name is #{name}.
puts "This author wrote this book #{book}." #<--- I want to write this or combine it with the line above
end
end
In class book, I don't have anything just
class Book < ActiveRecord::Base
end
How can I puts
the following:
That Author's name is ... and This author wrote this ...
when I enter Author.first.describe
in the Rails console?
Upvotes: 0
Views: 261
Reputation: 1428
based on the information you gave me in the comment your relations would look something like this:
class Author < ActiveRecord::Base
belongs_to :book
end
class Book < ActiveRecord::Base
has_one :author
end
The describe method in your Author class could look something like
def describe
"That Author's name is #{name}. This author wrote this book #{book.title}."
end
This is based on you stating you have the book_id in your authors table, and I am also assuming you have a title or name field in your books table.
However, it feels more natural to have the Author owning the book, and the book belonging to the Author, so might I suggest changing your data structure a bit to remove the book_id from authors table, and instead place an author_id in book table, and then your models relations would look like this:
class Author < ActiveRecord::Base
has_one :book
end
class Book < ActiveRecord::Base
belongs_to :author
end
Upvotes: 2
Reputation: 39
class Author < ActiveRecord::Base
has_many :books
class Book < ActiveRecord::Base
belongs_to :author
and in the migration author:references
class CreateServices < ActiveRecord::Migration[5.0]
def change
create_table :services do |t|
t.string :title
t.text :description
t.text :require
t.integer :price
t.references :user, foreign_key: true
t.timestamps
end
end
end
this is a project i'm working on, i'm using user but in your case is author.
Upvotes: 1