DrummerGenius
DrummerGenius

Reputation: 545

Unknown primary key for a table in a model (ActiveRecord)

I am trying to work on a search form which will take one or several optional parameters and query my model (Events) accordingly. So far, I am starting with two parameters: keyword, and tags.

An Event has and belongs to many tags. A tag has and belongs to many events. You can see those models here:

class Event < ApplicationRecord
    has_many :user_event_relationships
    has_many :map_markers
    has_many :users, through: :user_event_relationships
    has_and_belongs_to_many :tags
    has_one_attached :picture
    validates :name, :location, :date_to, :date_from, presence: true
    validate :valid_date_range_required, :valid_date, :image_type

    geocoded_by :location

    def image_type
        if picture.attached? && !picture.content_type.in?(%('image/jpeg image/png'))
            errors.add(:picture, "needs to be a jpeg or png!")
        end
    end

    def valid_date_range_required
        if (date_to.present? && date_from.present?) && (date_to < date_from)
            errors.add(:date_to, "Must be later than the from date!")
        end
    end

    def valid_date
        if date_from.present? && (date_from < DateTime.now)
            errors.add(:date_from, "Starting date cannot be in the past!")
        end
    end

    scope :with_name, proc { | name|
        if name.present?
            where("lower(name) like ?", "%#{name.downcase}%")
        end
    }

    scope :with_tag, proc { | tag|
        if tag.present?
            joins(:tags).where(tags: {name: Tag.find(tag).name})
        end
    }

    def self.filter(params)
        with_name(params[:keyword]).with_tag(params[:tags])
    end

    #def self.filter(params)
    #    #params.permit(SUPPORTED_FILTERS).to_hash.reduce(all) do |scope, (key, value)|
    #    #    value.present? ? scope.send(key, value) : scope
    #    #end
    #    debugger
    #    events = Event
    #    params.permit(SUPPORTED_FILTERS).to_hash.reduce(all) do |scope, (key, value)|
    #        debugger
    #        if key.to_sym == :keyword
    #            puts "keyword"
    #           events.where("lower(name) like ?", "%#{value.downcase}%")
    #        end
    #        if key.to_sym == :tags
    #            puts "tags"
    #            events.joins(:tags).where('tags.name = ?', Tag.find_by(name: value))
    #        end
    #        scope
    #    end
    #end
end
class Tag < ApplicationRecord
  has_and_belongs_to_many :events
end

My schema.rb file is as follows:

  create_table "events", force: :cascade do |t|
    t.string "name"
    t.integer "tags"
    t.datetime "date_from"
    t.datetime "date_to"
    t.string "location"
    t.decimal "latitude", precision: 10, scale: 6
    t.decimal "longitude", precision: 10, scale: 6
    t.string "description"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "tags", force: :cascade do |t|
    t.string "photo_url"
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "events_tags", id: false, force: :cascade do |t|
    t.bigint "event_id", null: false
    t.bigint "tag_id", null: false
    t.index ["event_id", "tag_id"], name: "index_events_tags_on_event_id_and_tag_id"
    t.index ["tag_id", "event_id"], name: "index_events_tags_on_tag_id_and_event_id"
  end

My goal is to be able to filter events based on a single tag name. For example, if I have "Basic Event 1" and "Basic Event 2" with the first having "Tag A" and the second having "Tag B", if I query for events with a name that contains 'Basic' and has "Tag A" I would only get the first event.

My self.filter command throws the following error:

*** ActiveRecord::UnknownPrimaryKey Exception: Unknown primary key for table events_tags in model Event::HABTM_Tags. 

Any help would be appreciated!

Upvotes: 0

Views: 1867

Answers (2)

Licke
Licke

Reputation: 191

I recently had similar issues like this and I found a solution.

  joins(:tags).where(tags: {id: tag})

The error

*** ActiveRecord::UnknownPrimaryKey Exception: Unknown primary key for table events_tags in model Event::HABTM_Tags.

You get this error currently because Tag.find(tag).name is not a primary key for the relation. Therefor it cant find any Tag 😉

Upvotes: 0

kevinluo201
kevinluo201

Reputation: 1663

Tag.find only accept primary key, which is ID column in convention. It raises error unless you give it a PK.
I guess you probably gave it a name string you wanted to query.

joins(:tags).where(tags: {name: Tag.find(tag).name})

# change to
joins(:tags).where(tags: { name: name })

It's apparently you used the find in wrong way in the where clause, because both use :find or :find_by_* methods should return only and exact one record if the record is found. It's contradict to how you wrote the query in the where()

Upvotes: 1

Related Questions