gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中的多对多多态关联

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:00 25 4
gpt4 key购买 nike

VideoSongArticle 可以有很多标签。每个标签也可以有很多视频、歌曲或文章。所以我有 5 个模型:Video、Song、Article、Tag 和 Taggings

这是这些模型:

class Video < ActiveRecord::Base
has_many :tags, :through => :taggings
end

class Song < ActiveRecord::Base
has_many :tags, :through => :taggings
end

class Article < ActiveRecord::Base
has_many :tags, :through => :taggings
end

class Tag < ActiveRecord::Base
has_many :articles
has_many :videos
has_many :songs
belong_to :taggings, :polymorphic => true #is this correct?
end

Taggings 的数据库定义

create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.string "taggable_type"
t.integer "taggable_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

标签模型:

class Taggings < ActiveRecord::Base
belongs_to :tag #is this correct?
belong_to :taggable, :polymorphic => true #is this correct?
end

我担心的问题是,我是否正确定义了模型(belongs_tohas_many?)?我的直觉告诉我,我错过了什么。我看过很多文章,但我对它们很困惑。

最佳答案

您需要这些更改:

class Video < ActiveRecord::Base # or Song, or Article
has_many :taggings, :as => :taggable # add this
has_many :tags, :through => :taggings # ok


class Tag < ActiveRecord::Base
# WRONG! Tag has no tagging_id
# belong_to :taggings, :polymorphic => true

has_many :taggings # make it this way

# WRONG! Articles are available through taggings
# has_many :articles

# make it this way
with_options :through => :taggings, :source => :taggable do |tag|
tag.has_many :articles, :source_type => 'Article'
# same for videos
# and for songs
end

关于with_options .

你的类 Taggings 似乎没问题除了它的名字。它必须是单数,标记:

class Tagging < ActiveRecord::Base # no 's'!
belongs_to :tag
belong_to :taggable, :polymorphic => true
end

关于ruby-on-rails - Ruby on Rails 中的多对多多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com