Rails 3 的 scope
在rails 2中关联俩个表时如下用:
User.find( :all, :joins => :profile, :conditions => ['profile.age = ?', 33])
User.joins(:profile).where('profile.age = ?', 33)
query = User.joins(:profile).where('profile.age = ?', 33)query.where('users.name = ?', name) unless name.nil?query.where('profile.email = ?', email) unless email.nil?query.all
class User scope :by_age, lambda do |age| joins(:profile).where('profile.age = ?', age) unless age.nil? end scope :by_name, lambda{ |name| where(name: name) unless name.nil? } scope :by_email, lambda do |email| joins(:profile).where('profile.email = ?', email) unless email.nil? endendUser.by_age(33).by_name(params[:name]).by_email(params[:email]).all
class Tag belongs_to :postendclass Post has_many :tags belongs_to :user scope :tagged, lambda do |tag| joins(:tags).where('tags.name = ?', tag).group('posts.id') endendclass User has_many :postsend# 标记为 'ruby-on-rails',并且是特定user的帖子User.where('users.id = ?', 232423).posts.tagged('ruby-on-rails').count