olegario
olegario

Reputation: 742

FK column name messed in Rails

So, I'm having my first in experience with Ruby on Rails. This is the second month, but somethings are still kind weird to me. In some cases I can do:

link.url = url

Where the Class Link has a FK to the Url Class. But in some cases, if I do:

equipment.category = category

The Rails start to complaining, saying:

ActiveModel::MissingAttributeError: can't write unknown attribute `equipment_id`

Why this happen? Every time I had to do it some changes in the tables about references I did:

add_reference :equipment, :category, foreign_key: true

So how can I do all Classes/Table behaviour like the first example?

EDIT 1:

My schema for Category and Equipment is this:

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

create_table "equipment", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
    t.index ["category_id"], name: "index_equipment_on_category_id"
end

EDIT 2 The associations in the classes are this:

class Category < ApplicationRecord
    # Associations
    has_many :equipment
    ...

class Equipment < ApplicationRecord
    # Associations
    has_one :category
    ...

Upvotes: 1

Views: 43

Answers (1)

hoffm
hoffm

Reputation: 2436

You want to use belongs_to for the class that has the foreign key, sp:

class Category < ApplicationRecord
    # Associations
    has_many :equipment
    ...

class Equipment < ApplicationRecord
    # Associations
    belongs_to :category
    ...

You might also run into some trouble because equipment is an irregularly inflected noun—it's its own plural in Rails. Using that kind of word for tables/models often involves to trial and error for me, and may ultimately be more trouble than it's worth.

Upvotes: 2

Related Questions