2011-03-25 22 views
2

我正在訪問我無法更改的數據庫,並且它有一個名爲attribute的列已定義。任何時候我嘗試訪問一個attribute,我會得到以下例外:如何在具有名爲'attribute'的列的數據庫上使用ActiveRecord? (DangerousAttributeError)

屬性?

class User < ActiveRecord::Base 
     def self.authenticate(username,password) 
     where(:username => username, :value => password).first 
     end 
end 

我發現在軌道上的郵件列表爲解決這一問題,但對我

class << self 
    def instance_method_already_implemented?(method_name) 
     return true if method_name == 'attribute' 
     super 
    end 
    end 
不行的紅寶石計劃:由ActiveRecord的(ActiveRecord的:: DangerousAttributeError)

我的代碼定義

我不知道它是否重要,但這裏是我的環境的細節:

  • ruby​​ 1.9.2p0(2010-08-18 revisi上 29036)[x86_64的-darwin10.4.0]
  • 滑軌
  • 3.0.1 ActiveRecord的(3.0.1)的ActiveResource(3.0.1)

UPDATE(解決):

PLAN甲:

select("username, value").where(:username => username, :value => password).first 
+0

是「屬性?」還是「屬性」的例外情況?注意問號在哪裏。 – 2011-03-25 06:10:27

+0

關於'attribute?'的例外。名爲'attribute' – jean 2011-03-25 06:18:02

回答

2

ActiveRecord的查詢支持:select參數,它可以讓你定義你想回到你作爲一個字符串的字段。

通常情況下人們使用這樣的:

:select => 'field1, field2' 

如果您知道原始查詢語言爲數據庫服務器,那麼你可以使用在選擇字符串。其中一個選項使用選擇字段時,SQL是使用as修改:

select field1 as the_first_field, field2 as the_second_field 

和數據庫將使用新的字段名,而不是舊的字段名返回的字段。如果你的數據庫支持這種方式,那麼這是一種簡單的方式來管理以與Rails衝突的方式命名的遺留字段。

請參閱Ruby on Rails指南中的「學習愛ActiveRecord:選擇參數」中的「Five ActiveRecord Tips」和「Selecting Specific Fields」。

下面是從我的Rails的一個示例應用使用的是該rails console訪問我的Postgres數據庫:

ruby-1.9.2-p180 :007 > dn = DomainName.first 
=> #<DomainName id: 1, domain_name: "ip72-208-155-230.ph.ph.cox.net", created_at: "2010-04-20 05:53:22", updated_at: "2010-04-20 05:53:22"> 
ruby-1.9.2-p180 :008 > dn = DomainName.first(:select => 'id, domain_name as dn') 
=> #<DomainName id: 1> 
ruby-1.9.2-p180 :009 > dn['id'] 
=> 1 
ruby-1.9.2-p180 :010 > dn['dn'] 
=> "ip72-208-155-230.ph.ph.cox.net" 
+0

謝謝你。我知道這個計劃,我使用原始查詢語言。但有時不安全。 – jean 2011-03-25 07:03:33

+0

這不是使用原始SQL,而是使用只是查詢的一部分的select語句。如果你沒有正確處理你的參數,'where'子句可能是不安全的。 – 2011-03-25 07:07:11

+0

但ActiveRecord仍然會嘗試爲'attribute'列創建所有方法。 – 2011-03-25 07:08:20

1

對於x柱,ActiveRecord的創建xx=,和x?方法。因此,更新修復這個:

class << self 
    def instance_method_already_implemented?(method_name) 
     return true if method_name == 'attribute?' 
     super 
    end 
end 
+0

的列發生了變化,並且出現錯誤'attribute_before_type_cast由ActiveRecord定義' – jean 2011-03-25 06:58:39

+0

如果將'method_name =='attribute_before_type_cast''返回true到'instance_method_already_implemented?'中的列表中,會發生什麼? – 2011-03-25 07:10:55

+0

請看我的更新,解決了它,但很多'返回true如果method_name ==' – jean 2011-03-25 09:12:18

0

也許你可以使用alias_attribute,因此使用具有不同名稱的方法。

相關問題