简体   繁体   中英

uninitialized constant NameError when use has_many

I practice my RoR skills and try develop application to already created DB. It's have 4 tables: testplans , testplan_tcversions ,* test_project* and nodes .

I'm code 2 models for this tables:

 class TestPlan < ActiveRecord::Base
  self.table_name= 'testplans'

  belongs_to :test_project

  has_many :test_suites, foreign_key: :testplan_id, inverse_of: :test_plan

  has_one :node, foreign_key: :id, inverse_of: :test_plan
end

and

class TestSuite < ActiveRecord::Base
  self.table_name='testplan_tcversions'
  belongs_to :test_plan

  has_one :node, foreign_key: id, inverse_of: :test_collection
end

But I get exception uninitialized constant TestPlan::TestSuite when try: @suits=TestPlan.find(4906).test_suites

I found a lot of answers that Models must singular and table must plural, but my Models names are singular, names of tables I point in self.table_name.

What I did wrong?

UPD

This my db:schema:dump

create_table "testplans", force: true do |t|
    t.integer "testproject_id"
    t.text    "notes"
    t.integer "active"
    t.integer "is_open"
    t.integer "is_public"
    t.text    "api_key"
  end

 create_table "testplan_tcversions", force: true do |t|
    t.integer  "testplan_id"
    t.integer  "tcversion_id"
    t.integer  "node_order"
    t.integer  "urgency"
    t.integer  "platform_id"
    t.integer  "author_id"
    t.datetime "creation_ts"
  end

How are your migrations set up?

If they are set up correctly, the relationship between TestSuite and TestPlan should look like this:

class TestPlan < ActiveRecord::Base
  has_many :test_suites
end

class TestSuite < ActiveRecord::Base
  belongs_to :test_plan
end

For this to work though, your TestSuite migration needs to have a test_plan_id column. That should look like this.

class TestSuite < ActiveRecord::Migration
  belongs_to :test_plan
end

If this is set up correctly, you should then be able to call @suits=TestPlan.find(4906).test_suites .

Make sure your table names correspond to your model names. If you don't have a table named 'testplan_tcversions', the association isn't going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM