mike9182
mike9182

Reputation: 289

has_many belongs_to assocation issue

I have two models: University and Market

A University belongs to a single Market, and a Market can have many universities. For example, An instance of Market like Boston might have University instances like MIT, Harvard, Boston University, etc.

I want to be able to do something like this in console:

University.first.market.name

But I get the following error:

NoMethodError: undefined method `market' for #

I can get the market id from University.first.market_id, but I can't get the name from market.name.

Here is how I have my models set up:

class University < ApplicationRecord
belongs_to :markets

class Market < ApplicationRecord
has_many :universities
end

And here is my schema - I think with the market_id integer column and index correctly implemented (?)

  create_table "universities", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "full_name"
    t.integer  "market_id"
    t.index ["market_id"], name: "index_universities_on_market_id"
end

Here's my markets schema:

  create_table "markets", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "name"
  end

What am I doing incorrectly?

Upvotes: 2

Views: 32

Answers (1)

Bruno Farias
Bruno Farias

Reputation: 913

In a one-to-many relationship, the "belongs_to" end must be singular, as below:

class University < ApplicationRecord
  belongs_to :market
end

class Market < ApplicationRecord
  has_many :universities
end

Let me know if that helps

Upvotes: 4

Related Questions