Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add new attributes to my rails models?

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:

Console output

What do I need to do to write the name into the database?

like image 635
nanobot Avatar asked Dec 09 '25 17:12

nanobot


1 Answers

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

  1. create a rails migration rails g migration add_fields_to_categories name:string attribute2:type attribute3:type

  2. run rails db:migrate

  3. reopen the console and create a new category with name attributes.

  4. Now check

like image 57
Gagan Gupta Avatar answered Dec 12 '25 07:12

Gagan Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!