【问题标题】:Seeding an ActiveRecord Database with objects from another table使用另一个表中的对象为 ActiveRecord 数据库播种
【发布时间】:2015-07-24 01:01:50
【问题描述】:

我是 Rails 新手,我正在制作我的第一个应用程序,但我有(另一个)问题:

我正在向我的抽认卡应用程序添加“卡片组”功能,但在建模以生成由卡片表中的卡片对象填充的“卡片组”时遇到了问题。

这是我的联想:

User has_many :decks

Deck belongs_to :user
Deck has_many :cards

Card belongs_to :deck




class Card < ActiveRecord::Base
  belongs_to :deck

  validates :front, presence: true
  validates :back, presence: true
  validates :deck_id, presence: true

end

这是我的套牌迁移/表格:

class Decks < ActiveRecord::Migration
  def change
    create_table :decks do |t|
      t.string :name, null: false
      t.string :card
      t.integer :user_id, null: false
    end
  end
end

我的问题是我希望卡片组表中的“卡片”列包含卡片对象,以便我可以访问/操作它们的方法,但我不确定如何执行此操作。我尝试用 ":card" 的 t.string 填充表格,希望这会起作用,但它只会出现空白。我想知道这是否可行或可取,还是有更好的方法?

如果有人能指出我的资源/提供这方面的建议,谢谢。我检查了文档/SO,似乎找不到任何东西。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    你所描述的很容易实现。

    如果User、Deck和Card是ActiveRecord模型,则可以通过设置外键连接表来关联它们。外键是一个integer 列,其中包含关联模型的id(其表的主键)

    Rails 约定是使用belongs_to 和has_many 来声明“一对多”关联(docs)。这些方法将向您的模型对象添加表示关联并与之交互所需的方法。

    在数据库模式方面,您需要在模型表上设置外键,以声明belongs_to 关联。

    所以,如果你有这些模型:

    class User < ActiveRecord::Base
      has_many :decks
    end
    
    class Deck < ActiveRecord::Base
      belongs_to :user
      has_many :cards
    end
    
    class Card < ActiveRecord::Base
      belongs_to :deck
    end
    

    您将需要这些迁移:

    class CreateDecks < ActiveRecord::Migration
      def change
        create_table :decks do |t|
          # your other columns...
          t.integer :user_id
        end
      end
    end
    
    class CreateCards < ActiveRecord::Migration
      def change
        create_table :cards do |t|
          # your other columns...
          t.integer :deck_id
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      使用 has_many 关系,您不会将外键存储在拥有表上。相反,您在卡片表中有一个 deck_id 列。

      一个使用关联的例子:

      # Load a deck and include the cards in the query
      @deck = Deck.joins(:cards).last
      
      @deck.cards.each do |card|
        puts card.front
      end
      
      # create a new card
      @deck.cards.new(front: 'foo', back: 'bar')
      @deck.save # will save the card as well.
      

      http://guides.rubyonrails.org/association_basics.html

      【讨论】:

        【解决方案3】:

        您不想在套牌表中出现card 列。模型中的 has_many :cards 和 belongs_to :deck 行提供了该功能,让您能够执行 @deck.cards 之类的操作。

        您只需要确保在创建新 Card 对象时分配一个 deck_id。

        您应该阅读 associations 和 database seeding 上的 Rails 指南。

        【讨论】:

        • 感谢大家的解释......我已经按照文档为我的卡片模型分配了一个 deck_id,但不明白这足以让所有访问卡片方法通过像@deck.cards 这样的表达式。虽然播种了我的数据库并且它可以工作。谢谢
        猜你喜欢
        • 2017-05-12
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        • 1970-01-01
        • 2013-06-21
        • 1970-01-01
        相关资源
        最近更新 更多