访问模型属性的rails返回nil

use*_*174 4 ruby-on-rails rails-activerecord

所以我上了一堂ItemActiveRecord::Base.我已经实施了这个show动作,以便我可以看到它items\id.在show.html.erb我已访问所有属性并在文件上标记它们.当我进入网页时,没有任何属性出现,只有他们的标签.然后我去看看出了什么问题.@item存储属性的对象出现了,但是当我逐个检查所有属性时,它们都是nil.有谁知道为什么会这样?

[时间戳] _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
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

items_controller.rb:

class ItemsController < ApplicationController

    def show
        @item = Item.find(params[:id])
        debugger
    end
end
Run Code Online (Sandbox Code Playgroud)

show.html.erb:

Name: <%= @item.name %>
Description: <%= @item.description %>
Price: <% @item.price %>
Run Code Online (Sandbox Code Playgroud)

控制台输出:

(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
Run Code Online (Sandbox Code Playgroud)

use*_*174 8

我想通了,我需要做的就是attr_accessor完全删除这条线.Rails 4在创建ActiveRecord对象时使用强参数,尽管在我的情况下我只显示它所以我不需要它.

  • 谢谢.这真的应该以某种方式记录在控制台中,只是浪费了太多时间试图弄清楚为什么一切都返回`nil`但是通过验证. (2认同)

Rya*_*igg 6

这是因为您已经使用以下方法覆盖了 ActiveRecord 提供的 getter 方法attr_accessor

attr_accessor :name, :description, :price
Run Code Online (Sandbox Code Playgroud)

您的意思是要使用attr_accessible吗?