sql - Rails Search Self Referential Relationship -
i trying allow users search through own friends email address. i'd like:
current_user.search('test@fake.com')
and have homecoming array of current users friends have email address.
so have basic friendship relationship set on user model
user.rb has_many :friendships has_many :friends, through: :friendships, source: :friend has_many :inverse_friendships, class_name: 'friendship', foreign_key: 'friend_id' has_many :inverse_friends, through: :inverse_friendships, source: :user friendship.rb belongs_to :friend, class_name: 'user', foreign_key: 'friend_id' belongs_to :user
i want set method on user model can search through friends email address. it's not working well
def search(query) conditions = ['friends.user_id = ? , email ? ', self.id, "%#{query}%"] user.includes(:friends).where(conditions) end
i guess i'm not sure how format active record query / sql here, since trying search on relations of self referential model. 1 have ideas?
thanks!
digital cake going in right direction, not correct. scope method of user, not user. need is:
def followers_by_email(email) friends.where("email ?", "%#{email}%") end
this returns activerecord::relation can chain other conditions, order, paginate, etc in
user.followers_by_email("me@example.com").order(:first_name).limit(10)
sql ruby-on-rails ruby-on-rails-3 rails-activerecord
No comments:
Post a Comment