2011-11-07 36 views
0

我被這個應用程序卡住了) 我有3個模型 - 用戶,照片和喜歡 用戶將登錄,查看照片並標記爲「喜歡」或「不喜歡」。 這裏是我的DB模式,微不足道領域跳過brewity:紅寶石在軌道上,如何實現關係

create_table "likes", :force => true do |t| 
    t.integer "oid"  # oid is photos.id 
    t.integer "user_id" # user who liked this photo 
    t.boolean "mark",  :default => true 
    end 

    create_table "photos", :force => true do |t| 
    t.string "photo" #filename of the photo 
    end 

    create_table "users", :force => true do |t| 
    t.string "firstname", 
    t.string "lastname", 
    t.string "email", 
    end 

這裏的模型:

class Photo < ActiveRecord::Base  
    has_many :likes, :foreign_key => 'oid' 
end 

class Like < ActiveRecord::Base 
    belongs_to :photo 
end 

class User < ActiveRecord::Base 
    has_many :likes, :through => :photos 
end 

一張照片都會有每個用戶一個標誌。即用戶不能'喜歡'兩次或更多的照片。

我希望用戶能夠看到他們在重新登錄後給出估計的照片。

現在,我選擇的照片下面的語句: @photos = Photo.limit(30).offset(0) 然後在模板: <%= photo.likes.where(「USER_ID =#{CURRENT_USER .id}「)%> 在此之後,我有30多個SQL查詢,換句話說,N + 1問題。

避免這個問題的一個選擇是在選擇照片時加入喜歡的選項。

@photos = Photo.includes(:likes).limit(30).offset(0) 

但是,這將包括所有用戶喜歡的照片,並對應用程序的性能產生不利影響。另外,我將不得不爲當前用戶提取記錄。

第二個選擇是創建動態關係

class User < ActiveRecord::Base 
    has_many :likes, :through => :photos, :conditions => "user_id = current_user.id" 
end 

對於這個選擇,我將不得不通過從控制器current_user.id模型,這看起來不正確我。

請幫助解決這個

回答

3

首先,這是一個設計問題。想想這個:「喜歡」是用戶和照片之間的某種聯繫。只要大聲說出:「許多用戶可能會喜歡一張照片;用戶可能會喜歡很多照片」。

是不是很清楚您的Like模型應該位於您的PhotoUser模型之間?現在

.----------.1 0..*.----------.0..* 1.----------. 
| users |<-------| likes |-------->| photos | 
'----------'  '----------'   '----------' 

class User < ActiveRecord::Base 
    has_many :likes 
    has_many :liked_photos, through: :likes, class: 'Photo' 
end 

class Like < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :photo 
    # this will ensure that your users can only like a photo once. 
    # you can also add a unique index to the two columns using 
    # add_index in a migration for more safety and performance. 
    validates_uniqueness_of [:user, :photo] 
end 

class Photo < ActiveRecord::Base 
    has_many :likes 
    has_many :liking_users, through: :likes, class: 'User' 
end 

,你就必須這樣做是爲了有效地檢索相關圖片:

@user = User.includes(likes: :photos).find(current_user.id) 
@photos = @user.liked_photos 
+0

看起來不錯 - 但需要使用「OID」外鍵爲適合它的工作。 –