ActiveAdmin没有方法错误

时间:2017-10-30 09:51:31

标签: ruby-on-rails activeadmin

我为我的模型和我的表添加了几个外键,因此我已经破坏了我对Active Admin的使用。我想知道是否有人知道解决这个问题或修复此问题。

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学生模特

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

我收到错误,是否有人为此找到了解决办法?

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

1 个答案:

答案 0 :(得分:1)

您已将关联定义错误。

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

belongs_to将外键放在此表上,正是您想要的。加入时,您希望在此表上拥有ID,而不必查找student_id匹配此记录的记录。

您还需要确保添加外键列和正确的外键约束:

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

我还强烈建议不要使用非标准主键。使用student_为PK添加前缀只会给您带来麻烦,并且会让其他开发人员感到困惑。