Question

I have two models that can have tags added to them.

  • Player
  • Ticket

and I have a Tag model which belongs to both so I have two join models

  • tag_ticket
  • tag_player

I am getting a Could not find the association :tag_tickets in model Ticket error but my association is in there.

class Ticket < ActiveRecord::Base
  has_many :tag_tickets
  has_many :tags, :through => :tag_tickets
end

I'm just focusing on the Ticket model but the player model should look similar.

this is my migration for TagTicket

class CreateTagTickets < ActiveRecord::Migration
  def change
    create_table :tag_tickets do |t|
      t.integer :ticket_id
      t.integer :tag_id

      t.timestamps
    end
  end
end
Was it helpful?

Solution

You need to specify the :tag_tickets join first like this:

class Ticket < ActiveRecord::Base
  has_many :tag_tickets
  has_many :tags, :through => :tag_tickets
end

You would also need to specify the joins in your TagTicket model:

class TagTicket < ActiveRecored::Base
  belongs_to :ticket
  belongs_to :tag
end

Alternatively, you can skip all this and use a habtm join (only recommended if the tag_tickets join is truly only used as a join and has no primary key for itself). In this case you would have no TagTicket model (just a tag_tickets table) and the Ticket model would look like this:

class Ticket < ActiveRecord::Base
  has_and_belongs_to_many :tags
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top