未定义的方法`klass'为零:NilClass

时间:2014-11-26 07:46:50

标签: ruby-on-rails activeadmin

我是Rails的新手,我对ORM关系有疑问。

当我访问/ admin / health_concerns_lists

显示。

Showing /Users/sbpipb/.rvm/gems/ruby-2.1.1/bundler/gems/activeadmin-a2cd9604c2d9/app/views/active_admin/resource/index.html.arb where line #2 raised:

undefined method `klass' for nil:NilClass
Extracted source (around line #2):
1

  insert_tag renderer_for(:index)

这是我的关系。

class HealthProfile < ActiveRecord::Base
    #table - health_profiles
    has_many :health_concerns, dependent: :destroy
    has_many :health_concerns_lists, :through => :health_concerns ,dependent: :destroy
end

class HealthConcern < ActiveRecord::Base
    #table - health_concerns
    belongs_to :health_profile
    belongs_to :health_concerns_list
end

class HealthConcernsList < ActiveRecord::Base
    self.table_name = "health_concerns_list"
    has_many :health_concerns, dependent: :destroy
    has_many :health_profiles, :through => :health_concerns_lists, dependent: :destroy
end

模式

health_profile
id
name

health_concerns
id
health_profile_id
health_concerns_id

health_concerns_list
id
name

我知道,我的命名惯例听起来不对。

3 个答案:

答案 0 :(得分:3)

class HealthProfile < ActiveRecord::Base
    #table - health_profiles
    has_many :health_concerns, dependent: :destroy
    has_many :health_concerns_lists, :through => :health_concerns ,dependent: :destroy
end

我想你需要纠正这个部分:

class HealthConcern < ActiveRecord::Base
    #table - health_concerns
    belongs_to :health_profile
    has_many :health_concerns_list
end

class HealthConcernsList < ActiveRecord::Base
    belongs_to :health_concerns, dependent: :destroy
    belongs_to :health_profiles, dependent: :destroy
end

答案 1 :(得分:1)

尝试更改

class HealthProfile < ActiveRecord::Base
    # ...
    has_many :health_concerns_lists, :through => :health_concerns, dependent: :destroy
end

成:

class HealthProfile < ActiveRecord::Base
    # ...
    has_many :health_concerns_lists, :through => :health_concerns, dependent: :destroy
    has_many :health_concerns
end

对于has_many through: ...

的每个型号

答案 2 :(得分:0)

尝试删除:

self.table_name = "health_concerns_list"

通过Rails约定,您无需为模型指定表名。他们的模型名称(HealthConcernsList)将为tableize'到health_conerns_lists

如果您必须使用单个table_name,请尝试:

class HealthConcernsList < ActiveRecord::Base
  self.pluralize_table_names = false
end

http://guides.rubyonrails.org/3_1_release_notes.html#active-record