activeadmin:父资源页面的模型必须与名称等于子资源页面名称的关联

时间:2015-01-12 10:45:43

标签: ruby-on-rails ruby activeadmin belongs-to

模型RegionCountry必须具有名为cities的关联(因为子资源页面生成名为CityController的控制器)

如何自定义关联名称?

回溯:

NoMethodError (undefined method `cities' for #<RegionCountry:0x0000000605f158>):
activemodel (4.0.9) lib/active_model/attribute_methods.rb:439:in `method_missing'
activerecord (4.0.9) lib/active_record/attribute_methods.rb:168:in `method_missing'
inherited_resources (1.5.1) lib/inherited_resources/base_helpers.rb:184:in `end_of_association_chain'

应用程序/管理/ region_city.rb

ActiveAdmin.register RegionCity, as: 'City' do
  permit_params :name, :description, :country_id
  menu false
  belongs_to :country, parent_class: RegionCountry
  navigation_menu :default
  filter :id_eq
end

PP /管理/ region_country.rb

ActiveAdmin.register RegionCountry, as: 'Country' do
  permit_params :name, :description
  filter :id_eq
  sidebar 'Links', only: [:show] do
    ul do
      li do
        link_to 'Cities', admin_country_cities_path(country_id: resource.id)
      end
    end
  end
end

应用程序/模型/ region_city.rb

class RegionCity < ActiveRecord::Base

  belongs_to :country, class_name: RegionCountry, foreign_key: :country_id

  validates :name, presence: true
  validates :country, presence: true
end

应用程序/模型/ region_country.rb

class RegionCountry < ActiveRecord::Base
  validates :name, presence: true

  has_many :reg_cities, class_name: RegionCity, foreign_key: :country_id
end

Gemfile.lock的

GIT
  remote: git://github.com/gregbell/active_admin.git
  revision: a2cd9604c2d949f5193791045385756cee0c6865

但如果我们更改了app / models / region_city.rb:

class RegionCountry < ActiveRecord::Base
  validates :name, presence: true
  has_many :cities, class_name: RegionCity, foreign_key: :country_id # this line was changed
end

它会正常工作

这里是重复错误的测试应用: https://github.com/senid231/activeadmin_test_belongs_to/tree/rename_child

1 个答案:

答案 0 :(得分:2)

默认情况下,Inherited Resources(由ActiveAdmin使用)假定集合 用于镜像资源名称的名称,该名称为ResourceCountry#cities和 解释了未定义的方法错误。更改控制器中的默认值 将解决问题:

ActiveAdmin.register RegionCity, as: 'City' do
  belongs_to :country, parent_class: RegionCountry

  controller do

    # Instruct inherited_resources on how to find the collection from the
    # parent resource (by default it is assumed to be `:cities`); instead
    # use `:reg_cities` as the name of the collection (from
    # `RegionCountry#reg_cities`):

    defaults collection_name: :reg_cities
  end
end

有关更多信息,请参阅overriding defaults的Inherited Resource的文档 细节。