【问题标题】:How to change the behaviour of 'find' method for any object?如何更改任何对象的“查找”方法的行为?
【发布时间】:2010-11-06 04:25:31
【问题描述】:

我的理解是,任何 rails 对象的 find 方法都需要该对象的 id 列。但我想使用该表的另一列找到该表/对象的一行。我怎么做 ?

例如我有如下的 userstats 模型:

create_table "userstats", :force => true do |t|
  t.integer  "user_id"
  t.integer  "no_of_wts"
  t.integer  "no_of_wtb"
  t.integer  "wts_reputation"
  t.integer  "wtb_reputation"
  t.integer  "overall_reputation"
  t.datetime "created_at"
  t.datetime "updated_at"
end  

我想使用 user_id(我的用户模型的外键)而不是使用 userstat 模型的默认唯一键来查找 userstat 模型的实例。

有什么建议吗?

我正在使用 Rails 3.0.1

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 models


    【解决方案1】:

    你可以做类似的事情

    Person.find_by_user_name
    Person.find_all_by_last_name
    

    文档地址:http://api.rubyonrails.org/classes/ActiveRecord/Base.html

    有一个非常古老的 Railscast...不确定所有细节是否保持不变,但可以让您了解 Railscast:http://railscasts.com/episodes/2-dynamic-find-by-methods

    【讨论】:

      【解决方案2】:

      对于你的问题:

      UserStat.find_all_by_user_id(5)
      

      find() 的一些其他例子:

      UserStat.find_all_by_wts_reputation_and_wtb_reputation(1,2)
      UserStat.find(:all, :conditions => { :no_of_wtb=> 5 })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-11
        • 1970-01-01
        • 2018-08-21
        • 2022-01-26
        • 2019-08-07
        相关资源
        最近更新 更多