我被這個應用程序卡住了) 我有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模型,這看起來不正確我。
請幫助解決這個
看起來不錯 - 但需要使用「OID」外鍵爲適合它的工作。 –