我是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
我的问题是,我希望卡组表中的“卡片”列由卡片对象组成,以便我可以访问/操纵它们的方法,但是我不确定如何做到这一点。我尝试用t.string的“:card”填充表,希望它能起作用,但只会空白。我想知道这是否可能或建议还是有更好的方法?
如果有人可以在这方面为我提供资源/建议,请谢谢。我检查了docs / SO,似乎找不到任何东西。
您所描述的内容可以轻松实现。
前提是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句