I am new to ruby on rails and I started creating a small project, but I got stuck. I have two entities one called Category and the other called bills. One category has many bills, so I have setup the Active records and DB Migration. In the bills DB migration I have defined a reference to Category, but when i try to create new bills I stumble upon the erro unknow attribute "category_id. I have checked the fields on the Bills table using rails console and there is a field Category_Id. So i have added to the bills migrations file the new directive column: Category_Id, and still I see the error. what am I doing wrong ?
class CreateCategories < ActiveRecord::Migration[7.0]
def change
create_table :categories do |t|
t.string :name
has_many :bills, dependent: :destroy
t.timestamps
end
end
end
In the first file, in the t.references statement, remove the column: Catogory_id argument. It’s superfluous because Rails will name the foreign key column :category_id by default. And it’s erroneous because Rails expects to see the column name as a Ruby Symbol, not a constant. In addition, “Catogory” is spelled incorrectly. If you really needed to specify the column name because the default name wasn’t appropriate, it would look like this: t.references :category, null: false, foreign_key: true, column: :example_id
In the second file, remove the entire has_many line. That belongs in the model, not the migration.
The naming convention for Rails DB columns is lower-case, underscore-separated. So dateOfPayment should be date_of_payment. And Description should be description.
Thanks a lot for your help. I have made the changes that you have suggested but I am still facing the same error.
class CreateBills < ActiveRecord::Migration[7.0]
def change
create_table :bills do |t|
t.string :description
t.decimal :amount
t.date :date_of_payment
t.references :category, null: false, foreign_key: true, column: :category_id
t.timestamps
end
end
end
class CreateCategories < ActiveRecord::Migration[7.0]
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
end
