rails 访问模型属性 return 无

rails accessing model attributes return nil

所以我从 ActiveRecord::Base 做了一个 Item class。我已经实施了 show 操作,以便我可以从 items\id 看到它。在 show.html.erb 中,我访问了所有属性并将它们标记在文件中。当我转到网页时,显示了 none 个属性,只有它们的标签。然后我去byebug看看哪里出了问题。存储属性的@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

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

控制台输出:

(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

这是因为您使用 attr_accessor:

覆盖了 ActiveRecord 提供的 getter 方法
attr_accessor :name, :description, :price

您是想改用 attr_accessible 吗?

我想通了,我需要做的就是完全删除 attr_accessor 行。 Rails 4 在创建 ActiveRecord 对象时使用了强参数,尽管在我的例子中我只是展示它,所以我不需要它。