ActiveRecord query on model methods
If I have the following code:
class User < ActiveRecord::Base
has_many :problems
attr_accessible :email, :password, :password_conf开发者_Python百科irmation, :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
When I try to do this in AR this is what the call looks like:
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
It gives me an error that it is not a column which is true, however it generates data just like active record would.
How can I search the output if this function as if it was a native active record column?
The way i usually do this is by using the model you want to return.
So if its addresses you want, something like:
def user_address
Address.joins(:users).where(:user_id => user.id)
end
This way you get an AR relation object back and you can chain them.
The method user_address
is supposed to be used in the code (mostly views), not to be passed to AR.
AR would require things to be more understood by the DB.
To DB sort (order) using the User#address column:
#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
It might also be wise to check if a user exist for a problem when
def user_address
self.user.try(:address) #just in case a problem doesn't have an associated user
end
精彩评论