Skip to content

has_many associations with custom foreign_key and primary_key break edit views. #1878

@submitteddenied

Description

@submitteddenied

Given two models, User and Invitation:

class User < ActiveRecord::Base
  #attribute :email
  has_many :invitations, primary_key: :email, foreign_key: :invitee_email
end

class Invitation < ActiveRecord::Base
  #attribute :invitee_email
  belongs_to :invitee, class_name: "User", primary_key: :email, foreign_key: :invitee_email
end

Rails admin throws a NoMethodError error when loading the edit page NoMethodError in RailsAdmin::Main#edit

ActionView::Template::Error (undefined method `email' for #<Invitation:0x007fb0e2adfc88>):
    17:   collection = if xhr
    18:     selected.map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key)] }
    19:   else
    20:     i = 0
    21:     controller.list_entries(config, :index, field.associated_collection_scope, false).map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_p
rimary_key)] }.sort_by {|a| [selected_ids.index(a[1]) || selected_ids.size, i+=1] }
    22:   end
    23: 
  activemodel (4.0.2) lib/active_model/attribute_methods.rb:439:in `method_missing'
  activerecord (4.0.2) lib/active_record/attribute_methods.rb:155:in `method_missing'
  rails_admin (0.6.0) app/views/rails_admin/main/_form_filtering_multiselect.html.haml:20

I tracked this down to be on line 21 where field.associated_primary_key is sent to o, this needs to be field.foreign_key.

I'll submit a pull request soon (if I make this change it fixes my issue), but I'm not sure what else my change might break.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions