【问题标题】:Unknown primary key for a table in a model (ActiveRecord)模型中表的未知主键 (ActiveRecord)
【发布时间】:2020-07-31 14:15:44
【问题描述】:

我正在尝试使用一个搜索表单,该表单将采用一个或多个可选参数并相应地查询我的模型(事件)。到目前为止,我从两个参数开始:关键字和标签。

一个事件有并且属于许多标签。一个标签拥有并属于许多事件。您可以在此处查看这些模型:

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

我的schema.rb文件如下:

  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

我的目标是能够根据单个标签名称过滤事件。例如,如果我有“基本事件 1”和“基本事件 2”,第一个有“标签 A”,第二个有“标签 B”,如果我查询名称包含“基本”并且有“标记 A" 我只会得到第一个事件。

我的 self.filter 命令抛出以下错误:

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

任何帮助将不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    Tag.find 只接受主键,即约定的 ID 列。 除非您给它一个 PK,否则它会引发错误。
    我猜你可能给了它一个你想查询的名字字符串。

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

    显然你在 where 子句中以错误的方式使用了 find, 因为两者都使用:find:find_by_* 方法应该只返回并且如果找到记录则准确。这与您在 where() 中编写查询的方式相矛盾

    【讨论】:

      【解决方案2】:

      我最近遇到了类似的问题,我找到了解决方案。

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

      错误

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

      您当前收到此错误是因为Tag.find(tag).name 不是关系的主键。因此它找不到任何标签?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 2020-07-19
        • 2019-01-17
        • 2015-01-06
        • 2015-05-13
        • 2013-08-06
        • 1970-01-01
        相关资源
        最近更新 更多