gpt4 book ai didi

ruby-on-rails - 如何在具有名为 'attribute' 的列的数据库上使用 ActiveRecord? (危险属性错误)

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:18 24 4
gpt4 key购买 nike

我正在访问一个我无法更改的数据库,它定义了一个名为 attribute 的列。每当我尝试访问 attribute 时,我都会收到此异常:

属性?由 ActiveRecord(ActiveRecord::DangerousAttributeError) 定义

我的代码:

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

我在 ruby​​ on rails 邮件列表上找到了一个解决问题的计划,但对我不起作用

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

我不确定这是否重要,但这里是我的环境的详细信息:

  • ruby 1.9.2p0(2010-08-18 修订版29036) [x86_64-darwin10.4.0]
  • rails
  • 3.0.1 事件记录 (3.0.1) 事件资源 (3.0.1)

更新(已解决):

计划 A:

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

最佳答案

ActiveRecord 查询支​​持 :select 参数,它允许您将要返回给您的字段定义为字符串。

通常人们使用类似的东西:

:select => 'field1, field2'

如果您知道数据库服务器的原始查询语言,那么您可以在选择字符串中使用它。使用 SQL 选择字段时的选项之一是使用 as 修饰符:

select field1 as the_first_field, field2 as the_second_field

数据库将使用新的字段名而不是旧的字段名返回字段。如果您的数据库支持,这是一种管理以与 Rails 冲突的方式命名的遗留字段的简单方法。

请参阅 Ruby on Rails 指南中的“Five ActiveRecord Tips”和“Selecting Specific Fields”中的“学会爱上 ActiveRecord 的 :select 参数”。

这是我的一个 Rails 应用程序使用 rails 控制台 访问我的 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"

关于ruby-on-rails - 如何在具有名为 'attribute' 的列的数据库上使用 ActiveRecord? (危险属性错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5428987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com