ActiveRecord查询模型方法

时间:2011-06-25 03:36:55

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

如果我有以下代码:

class User < ActiveRecord::Base
  has_many :problems

  attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :location, :address

  attr_internal_accessor :user_address

  def user_address
    self.address
  end

end

class Problem < ActiveRecord::Base
  belongs_to :user

  validates_presence_of :user_id, :title, :description, :tags
  delegate :address, :to => :user, :prefix => true

end

当我尝试在AR中执行此操作时,这就是调用的样子:

Problem Load (0.2ms)  SELECT "problems".* FROM "problems" ORDER BY problems.user_address asc LIMIT 20 OFFSET 0
SQLite3::SQLException: no such column: problems.user_address: SELECT  "problems".* FROM "problems" ORDER BY problems.user_address asc LIMIT 20 OFFSET 0
Completed 500 Internal Server Error in 173ms

它给我一个错误,它不是一个真实的列,但是它会像活动记录那样生成数据。

如果此函数好像是本机活动记录列,我如何搜索输出?

2 个答案:

答案 0 :(得分:1)

我通常这样做的方法是使用你想要返回的模型。

所以,如果你想要它的地址,比如:

def user_address
  Address.joins(:users).where(:user_id => user.id)
end

这样你就可以得到一个AR关系对象,你可以链接它们。

答案 1 :(得分:1)

方法user_address应该在代码中使用(主要是视图),而不是传递给AR。

AR需要DB更好地理解事物。

使用用户#地址栏进行数据库排序(订单):

#Rails 3
p = Problem.includes(:user).order("users.address ASC").first
p.user_address

#Rails 2
p = Problem.find(:first, :include => :user, :order => "users.address ASC")
p.user_address

时检查用户是否存在问题也是明智之举
def user_address
  self.user.try(:address) #just in case a problem doesn't have an associated user
end