[英]rails accessing model attributes return nil
So I made an Item
class from ActiveRecord::Base
. 所以我从
ActiveRecord::Base
了一个Item
类。 I've implemented the show
action so that I could see it from items\\id
. 我已经实现了
show
动作,以便我可以从items\\id
看到它。 In show.html.erb
I have accessed all the attributes and labeled them on the file. 在
show.html.erb
我访问了所有属性并在文件上标记了它们。 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
. 存储属性的
@item
对象出现了,但是当我逐个检查所有属性时,它们都是nil
。 Does anyone know why this is happening? 有谁知道为什么会这样?
[timestamp]_create_items.rb: [时间戳] _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: 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: items_controller.rb:
class ItemsController < ApplicationController
def show
@item = Item.find(params[:id])
debugger
end
end
show.html.erb: 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. 我想通了,我需要做的就是彻底删除
attr_accessor
线。 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. Rails 4在创建ActiveRecord对象时使用强参数,尽管在我的情况下我只显示它所以我不需要它。
This is because you've overridden the getter methods ActiveRecord provides by using attr_accessor
: 这是因为您使用
attr_accessor
覆盖了ActiveRecord提供的getter方法:
attr_accessor :name, :description, :price
Did you mean to use attr_accessible
instead? 你的意思是使用
attr_accessible
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.