How to change the behaviour of 'find' method for any object?
My understanding is that the find method for any rails object will expect the id column of that object. But I want to find a row of that table/object using another column of that table. How do I do that ?
For example I have userstats model as follows:
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
I want to find an instance of userstat model using the user_id (my foreign key to user开发者_开发技巧 model) and not using the default unique key of userstat model.
Any suggestions?
I'm using Rails 3.0.1
You can do things like
Person.find_by_user_name
Person.find_all_by_last_name
docs at: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
There is a really old Railscast... not sure if all the details remain the same, but can get you introduced to Railscast: http://railscasts.com/episodes/2-dynamic-find-by-methods
For your problem:
UserStat.find_all_by_user_id(5)
Some other examples of find():
UserStat.find_all_by_wts_reputation_and_wtb_reputation(1,2)
UserStat.find(:all, :conditions => { :no_of_wtb=> 5 })
精彩评论