Vesuvious
Vesuvious

Reputation: 121

ActiveAdmin No method error

I added a couple of foreign keys to my models and to my tables and it has since broken my use of Active Admin. I'm wondering if anyone knows a work around or a fix to this issue.

schmea.rb

create_table "students", primary_key: "student_id", id: :string, force: 
:cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string "last_name"
    t.string "first_name"
    t.string "home_address"
    t.string "home_city"
    t.string "home_state"
    t.string "home_zip"
    t.string "school_year_address"
    t.string "school_year_city"
    t.string "school_year_zip"
    t.string "room_number"
    t.string "home_phone"
    t.string "cell_phone"
    t.boolean "new_student"
    t.boolean "returning_student"
    t.string "athletic_team"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "fk_rails_148c9e88f4"
end
add_foreign_key "emergency_contacts", "students", primary_key: "student_id"
add_foreign_key "students", "users"
add_foreign_key "vehicles", "students", primary_key: "student_id"

student.rb Students Model

class Student < ApplicationRecord
    self.primary_key = :student_id
    belongs_to  :user
    has_one :emergency_contact
    has_one :vehicle
end

I'm getting the error, has anyone found a fix for this?

undefined method `emergency_contact_id_eq' for Ransack::Search<class: Student, base: Grouping <combinator: and>>:Ransack::Search

Upvotes: 0

Views: 281

Answers (1)

max
max

Reputation: 101811

You have defined the assocation wrong.

class Student < ApplicationRecord
    self.primary_key = :student_id
    belongs_to  :user
    belongs_to :emergency_contact, class_name: 'User'
    has_one :vehicle
end

belongs_to places the foreign key on this table and is exactly what you want. When joining you want to have the id on this table instead of having to look for records where student_id matches this record.

You also need to make sure to add a foreign key column and the correct foreign key constraint:

class AddEmergencyContactIdToStudents < ActiveRecord::Migration[5.0]
  def change
    add_reference :students, :emergency_contact, foreign_key: false
    add_foreign_key :students, :users, column: :emergency_contact_id, 
  end
end

I would also strongly advise against using non standard primary keys. Prefixing the PK with student_ gives you nothing but headaches and will confuse other developers.

Upvotes: 1

Related Questions