简体   繁体   English

从另一个类中调用一个类-Ruby on Rails

[英]Call a class from another class - Ruby on Rails

I searched around the SOF and couldn't find a simple answer for my simple question. 我在SOF周围搜索,但找不到我的简单问题的简单答案。

I have two classes, Author and Book . 我有两个类, AuthorBook

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? 我怎样才能puts以下内容: That Author's name is ... and This author wrote this ...当我进入Author.first.describe在Rails的控制台?

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 Author类中的describe方法可能类似于

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. 这是基于您的陈述,即您在authors表中有book_id,并且我还假设您在books表中有一个title或name字段。

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: 但是,让作者拥有这本书并属于该作者是很自然的事情,所以我建议您稍微改变一下数据结构以从authors表中删除book_id,然后将author_id放在book表中,那么您的模型关系将如下所示:

class Author < ActiveRecord::Base
    has_one :book
end

class Book < ActiveRecord::Base
    belongs_to :author
end
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. 这是我正在处理的项目,正在使用用户,但在您的情况下是作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM