I created a model using: rails g model category
Now I want to add some attributes to that model like a name
so I went to the model and added the line attribute :name
class Category < ApplicationRecord
attribute :name
#has_many :posts
end
This is how my Controller looks like:
class CategoriesController < ApplicationController
#def permitted_params
# params.require(:category).permit(:name)
#end
def index
end
def new
end
def create
#category.create(permitted_params)
end
def edit
end
def update
end
def show
end
def destroy
end
end
Then I run the command : rails db:migrate and I wanted to add some stuff to my database to test it out.
I used the rails console and tryed to add a category:

What do I need to do to write the name into the database?
The attribute you're defining in your model is a virtual attribute and will not write anything to the database.
you'll have to define a migration to add columns/attributes to the database.
steps:
1. remove the attribute :name from category.rb
create a rails migration rails g migration add_fields_to_categories name:string attribute2:type attribute3:type
run rails db:migrate
reopen the console and create a new category with name attributes.
Now check
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With