4

Here is the structure I'm working with:

app/models/model.rb

class Model < ActiveRecord::Base
    attr_accessor :some_var
end

app/models/model_controller.rb

class ModelsController < ApplicationController
    def show
        @model = Model.find(params[:id])
        @other_var
        if @model.some_var.nil?
            @model.some_var = "some value"
            @other_var = "some value"
        else
            @other_var = @model.some_var
        end
    end
end

Whenever I run this code (e.g. the show method), the if clause is evaluated to be true (e.g. @model.some_var == nil). How do I get around this? Is there something wrong in my assumption of how attr_accessor works?

cih
  • 1,960
  • 1
  • 16
  • 27
tanookiben
  • 22,575
  • 8
  • 27
  • 25

1 Answers1

13

attr_accessor is a built-in Ruby macro which will define a setter and a getter for an instance variable of an object, and doesn't have anything to do with database columns with ActiveRecord instances. For example:

class Animal
  attr_accessor :legs
end

a = Animal.new
a.legs = 4
a.legs #=> 4

If you want it to be saved to the database, you need to define a column in a migration. Then ActiveRecord will create the accessor methods automatically, and you can (should) remove your attr_accessor declaration.

hdgarrood
  • 2,141
  • 16
  • 23
  • Ah, okay. It turns out I didn't really know how to save this particular attribute, because I need some_var to be a hash, and I knew that I couldn't simply define a column to be a hash, so now I'm going to use serialize to get the job done. – tanookiben Oct 17 '12 at 22:50
  • 1
    (Although its been long since you posted this question) If you are using postgres you can use a jsonb type column to store hash.. – Aitizazk Dec 30 '16 at 07:46
  • if animal has many categorys how can category table have access to the accessor attributes of animal. @hdgarrood – gangothri Feb 11 '22 at 12:15