首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从另一个类- Rails调用类

从另一个类- Rails调用类
EN

Stack Overflow用户
提问于 2017-01-31 00:35:31
回答 2查看 222关注 0票数 0

我在SOF周围搜寻,找不到简单的答案来回答我的简单问题。

我有两门课,AuthorBook

代码语言:javascript
运行
复制
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控制台中输入putsThat Author's name is ... and This author wrote this ...

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-31 02:13:45

根据你在评论中给我的信息,你们的关系会是这样的:

代码语言:javascript
运行
复制
class Author < ActiveRecord::Base
    belongs_to :book
end

class Book < ActiveRecord::Base
    has_one :author
end

您的Author类中的describe方法看起来可能如下所示

代码语言:javascript
运行
复制
def describe
  "That Author's name is #{name}. This author wrote this book #{book.title}."
end

这是基于您声明您的作者表中有book_id,而且我还假设您的图书表中有一个标题或名称字段。

然而,让作者拥有这本书和属于作者的书似乎更自然,所以我可能建议稍微改变数据结构,从authors表中删除book_id,然后在图书表中放置一个author_id,然后您的模型关系将如下所示:

代码语言:javascript
运行
复制
class Author < ActiveRecord::Base
    has_one :book
end

class Book < ActiveRecord::Base
    belongs_to :author
end
票数 2
EN

Stack Overflow用户

发布于 2017-01-31 01:39:14

代码语言:javascript
运行
复制
class Author < ActiveRecord::Base
has_many :books

class Book < ActiveRecord::Base
belongs_to :author

在迁移中作者:参考文献

代码语言:javascript
运行
复制
 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

这是我正在做的一个项目,我使用的是用户,但在您的例子中是作者。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41947868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档