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
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.
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