【问题标题】:Ruby on Rails ActiveRecord selectRuby on Rails ActiveRecord 选择
【发布时间】:2015-05-03 11:26:55
【问题描述】:

我正在尝试使用 Ruby on Rails 创建一个 ActiveRecord 数据库

我已经创建了一个数据库Schema

创建表destinations,productions,rules我正在使用rails generate model Name parameter:integer

如何使用外键创建表rule_input

另外,如何创建一个表或模型sources 来连接所有这些表,我可以获得如下来源:source = Source.find(1) 和例如render json: {source: source}

【问题讨论】:

    标签: ruby-on-rails database sqlite activerecord


    【解决方案1】:

    How to create a table rule_input with foreign key to rule?

    假设您要求 cli 命令 - “rails generate model rule_input rule:references”

    Also, how to create a table or a model sources that would join all these tables and I could get source like: source = Source.find(1) and for example render json: {source: source}?

    单表继承在这里可能是一个可能的解决方案。

    class Source < ActiveRecord::Base; end
    
    class Rule < Source
      has_many :rule_inputs 
    end
    
    class Production < Source; end
    class Destination < Source; end
    
    class RuleInput < ActiveRecord::Base
      belongs_to :rule
    end
    

    基本上,单表继承允许不同模型从单个表中的父模型继承,只要模型之间的数据结构非常相似,这对您来说是一个可行的选择。 (STI 消除了 3 个具有所有相同列的表)

    【讨论】:

    • 以及如何生成Source模型?
    • @TomKortney rails g model source value type,这里需要一个类型列,因为活动记录使用类型来确定它是哪个子模型。
    • 另外,我需要将模型视为对象还是表格?
    • @TomKortney 我在答案中添加了一个简短的解释。希望对您有所帮助。
    【解决方案2】:

    正如@maxhungry 提到的,您可以使用 STI(单表继承)来消除使用三个表的规则、产品和目标,并使用源模型将其替换为“类型”列。

    这里有一些关于 STI 和重构此类模型的好文章。

    https://about.futurelearn.com/blog/refactoring-rails-sti/

    http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-1/

    关于你的问题 - do I need to think about model as an object or as a table? 模型与表不同,因为我们可以有无表模型。您可以阅读此Rails model without a table。因此,如果您从 ActiveRecord::Base 子类化您的模型,那么它将指向一个表。比如这段代码

    class Product < ActiveRecord::Base
    end
    

    这将创建一个产品模型,映射到数据库中的产品表。但如果你只是说

    class Product
    end
    

    然后它是一个无表模型。

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多