Guest User

Untitled

a guest
Jun 21st, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. create_table "animal_friends", :force => true do |t|
  2. t.integer "animal_id"
  3. t.integer "animal_friend_id"
  4. t.datetime "created_at"
  5. t.datetime "updated_at"
  6. t.integer "status_id", :default => 1
  7. end
  8.  
  9. SELECT animals.*
  10. from animals join animal_friends as af
  11. on animals.id =
  12. case when af.animal_id = #{id} then af.animal_friend_id else af.animal_id end
  13. WHERE #{id} in (af.animal_id, af.animal_friend_id)
  14.  
  15. has_many :friends, :class_name => "Animal", :finder_sql => 'SELECT animals.* from animals join animal_friends as af on animals.id = case when af.animal_id = #{id} then af.animal_friend_id else af.animal_id end ' +
  16. 'WHERE #{id} in (af.animal_id, af.animal_friend_id) and status_id = #{Status::CONFIRMED.id}'
  17.  
  18. @animal.friends.first
  19.  
  20. CREATE VIEW with_inverse_animal_friends (
  21. SELECT id,
  22. animal_id,
  23. animal_friend_id,
  24. created_at,
  25. updated_at,
  26. status_id
  27. FROM animal_friends
  28. UNION
  29. SELECT id,
  30. animal_friend_id AS animal_id,
  31. animal_id AS animal_friend_id,
  32. created_at,
  33. updated_at,
  34. status_id
  35. FROM animal_friends
  36. )
  37.  
  38. CREATE VIEW unique_animal_friends (
  39. SELECT MIN(id), animal_id, animal_friend_id, MIN(created_at), MAX(updated_at), MIN(status_id)
  40. FROM
  41. (SELECT id,
  42. animal_id,
  43. animal_friend_id,
  44. created_at,
  45. updated_at,
  46. status_id
  47. FROM animal_friends
  48. UNION
  49. SELECT id,
  50. animal_friend_id AS animal_id,
  51. animal_id AS animal_friend_id,
  52. created_at,
  53. updated_at,
  54. status_id
  55. FROM animal_friends) AS all_animal_friends
  56. GROUP BY animal_id, animal_friend_id
  57. )
  58.  
  59. class Animal < ActiveRecord::Base
  60. has_many :unique_animal_friends
  61. has_many :friends, :through => :unique_animal_friends
  62. end
  63.  
  64. class UniqueAnimalFriend < ActiveRecord::Base
  65. belongs_to :animal
  66. belongs_to :friend, :class_name => "Animal"
  67. end
Add Comment
Please, Sign In to add comment