Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails accessing model attributes return nil

So I made an Item class from ActiveRecord::Base. I've implemented the show action so that I could see it from items\id. In show.html.erb I have accessed all the attributes and labeled them on the file. When I went to the web page, none of the attributes showed up, only their labels. I then went to byebug to see what went wrong. The @item object that was storing the attributes showed up, but when I checked all of the attributes one-by-one, they were all nil. Does anyone know why this is happening?

[timestamp]_create_items.rb:

class CreateItems < ActiveRecord::Migration
    def change
        create_table :items do |t|
            t.string :name
            t.text :description
            t.decimal :price

            t.timestamps null: false
        end
    end
end

item.rb:

class Item < ActiveRecord::Base
    attr_accessor :name, :description, :price
    validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
    validates :description, presence: true,
        length: { maximum: 1000 }
    VALID_PRICE_REGEX = /\A\d+(?:\.\d{0,2})?\z/
    validates :price, presence: true,
        :format => { with: VALID_PRICE_REGEX },
        :numericality => {:greater_than => 0}
end 

items_controller.rb:

class ItemsController < ApplicationController

    def show
        @item = Item.find(params[:id])
        debugger
    end
end

show.html.erb:

Name: <%= @item.name %>
Description: <%= @item.description %>
Price: <% @item.price %>

console output:

(byebug) @item
#<Item id: 1, name: "Ruby Gem", description: "A real Ruby Gem, the stone, not the software.", price: #<BigDecimal:ce58380,'0.1337E4',9(18)>, created_at: "2015-03-14 08:15:31", updated_at: "2015-03-14 08:15:31">
(byebug) @item.name
nil
(byebug) @item.description
nil
(byebug) @item.price
nil
like image 656
user2361174 Avatar asked Dec 11 '22 00:12

user2361174


1 Answers

I figured it out, all I needed to do was to remove the attr_accessor line completely. Rails 4 uses strong parameters when it comes creating an ActiveRecord object, although in my case I'm only showing it so I do not need it.

like image 66
user2361174 Avatar answered Jan 02 '23 00:01

user2361174