我在SOF周围搜寻,找不到简单的答案来回答我的简单问题。
我有两门课,Author和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在课堂上,我什么都没有
class Book < ActiveRecord::Base end
如何在Rails控制台中输入puts:That Author's name is ... and This author wrote this ...?
发布于 2017-01-31 02:13:45
根据你在评论中给我的信息,你们的关系会是这样的:
class Author < ActiveRecord::Base
    belongs_to :book
end
class Book < ActiveRecord::Base
    has_one :author
end您的Author类中的describe方法看起来可能如下所示
def describe
  "That Author's name is #{name}. This author wrote this book #{book.title}."
end这是基于您声明您的作者表中有book_id,而且我还假设您的图书表中有一个标题或名称字段。
然而,让作者拥有这本书和属于作者的书似乎更自然,所以我可能建议稍微改变数据结构,从authors表中删除book_id,然后在图书表中放置一个author_id,然后您的模型关系将如下所示:
class Author < ActiveRecord::Base
    has_one :book
end
class Book < ActiveRecord::Base
    belongs_to :author
end发布于 2017-01-31 01:39:14
class Author < ActiveRecord::Base
has_many :books
class Book < ActiveRecord::Base
belongs_to :author在迁移中作者:参考文献
 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这是我正在做的一个项目,我使用的是用户,但在您的例子中是作者。
https://stackoverflow.com/questions/41947868
复制相似问题