Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One to Many in Polymorphic Association

Based on my previous question, I am building a polymorphic association. I wanted to have one to many relationship as well. So I have created a new table/model posties/Posty to manage this relationship

A post can belong to multiple players and multiple teams.

Models:

class Posty < ActiveRecord::Base
    belongs_to :posts
    belongs_to :target, :polymorphic => true
end

class Post < ActiveRecord::Base
    has_many :posties
    has_many :players, :through => :posties
end

class Player < ActiveRecord::Base
    has_many :posts,:as => :target, :through => :posties
end

Tables:

  create_table "posties", id: false, force: true do |t|
    t.integer  "posty_id"
    t.string   "posty_type", limit: 30
    t.integer  "post_id"
  end

  create_table "posts", force: true do |t|
    t.integer  "user_id"
    t.date     "post_date"
    t.string   "title"
  end

  create_table "players", force: true do |t|
    t.string   "name"
  end

When I do, Player.find(1).posts, I get

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :posties in model Player

What could be wrong?

like image 795
Lenin Raj Rajasekaran Avatar asked Dec 07 '25 06:12

Lenin Raj Rajasekaran


1 Answers

You could probably do away with this intermediary Posty class, as only need a join table/model for a many-many association.But that aside, you need to fix the setup.

The polymorphic column names should be based on the association name.

create_table "posties", force: true do |t|
  t.integer  "target_id"
  t.string   "target_type", limit: 30
  t.integer  "post_id"
end

class Posty < ActiveRecord::Base
  belongs_to :post
  belongs_to :target, :polymorphic => true
end

class Post < ActiveRecord::Base
  has_many :posties
  has_many :players, :through => :posties, :as => :target
end

class Player < ActiveRecord::Base
  has_many :posties, :as => :target
  has_many :posts, :through => :posties
end

Edit:

I better just add that this probably still won't work. Im fairly sure you cannot have a has_many though a polymorphic association. In which case you should remove the Posty class, or get very creative!

create_table "posts" do |t|
  t.integer  "target_id"
  t.string   "target_type", limit: 30
end

class Post < ActiveRecord::Base
  belongs_to :target, :polymorphic => true
end

class Player < ActiveRecord::Base
  has_many :posts, :as => :target
end
like image 104
S.Spencer Avatar answered Dec 11 '25 05:12

S.Spencer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!