1
新手欄杆問題即將到來。Rails屬性頭痛
我有這樣一個類:
class Thing < ActiveRecord::Base
attr_accessible :name
attr_accessor :name
validates_uniqueness_of :name, :case_sensitive => false
end
我已經做了遷移和表沒問題。然後我火了rails console
和嘗試以下操作:
t = Thing.new(:name => "test")
=> #<Thing id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>
已經在這裏,它說的名字是零,爲什麼呢? 繼續,我試試這個:
t.name
=> "test"
現在名字似乎無論如何設置? 如果我試圖保存:
t.save!
Thing Exists (8.0ms) SELECT 1 AS one FROM "things" WHERE LOWER("things"."name") = LOWER('test') LIMIT 1
SQL (16.0ms) INSERT INTO "things" ("created_at", "description", "name", "updated_at") VALUES ('2012-10-28 16:10:12.701000', NULL, NULL, '2012-10-28 16:10:12.701000')
=> true
爲什麼名字我指定不救? 我想要的是在調用new時能夠將屬性指定爲散列,然後保存該實例。
點上。爲了闡述這個答案,當你想要一個沒有保存到數據庫的'虛擬屬性'時,你只需要'attr_accessor'。如果你的表中有一個'name'字段,ActiveRecord會爲你自動創建'#name'和'#name ='方法。 –
甜蜜,謝謝你幫幫忙! – oskbor