【问题标题】:Rails : Has_Many Through polymophic Could not find the association in modelRails:Has_Many通过多态找不到模型中的关联
【发布时间】:2014-01-26 06:20:02
【问题描述】:

我前面有个小问题,我试着让一个多态有很多通过关联:

post.rb

has_many :categories, as: :categorizable, through: :categorizations

category.rb

has_many :categorizables, through: :categorizations,dependent: :destroy

event.rb

has_many :categories, as: :categorizable, through: :categorizations

分类.rb

belongs_to :categorizable, :polymorphic => true

belongs_to :category

我的迁移:

定义改变

create_table :categories do |t|
  t.string :name

  t.timestamps
end

create_table :categorizations do |t|
  t.references :category

  t.integer :categorizable_id, :polymorphic => true
  t.string :categorizable_type, :polymorphic => true

  t.datetime :created_at
end

add_index :categorizations, :category_id   

结束

问题:

我收到了这个错误:

找不到关联:模型帖子中的分类

或者当我在类别中尝试时

找不到关联:模型类别中的分类

有谁知道问题出在哪里?

【问题讨论】:

  • 有什么问题?有什么错误吗?
  • 责备我!我编辑我的问题!

标签: ruby-on-rails ruby activerecord has-many-through polymorphic-associations


【解决方案1】:

您还需要在CategoryPostEvent 中指定:categorizations 关联。此外,您的 as 选项应该转到 categorizations 关联,因为这是您具有多态性的地方。

Post类:

class Post < ActiveRecord::Base
  has_many :categorizations, as: :categorizable
  has_many :categories, through: :categorizations
  # ...
end

你应该以类似的方式修改Event类。

Category类:

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :categorizables, through: :categorizations, dependent: :destroy
  # ...
end

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多