簡體   English   中英

紅寶石在軌,如何實現關系

[英]ruby on rails, how to implement relations

我被這個應用程序卡住了)我有3種模型-用戶,照片和喜歡用戶將登錄,查看照片並將它們標記為“喜歡”或“不喜歡”。 這是我的數據庫架構,為簡化起見,忽略了一些無關緊要的字段:

  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從控制器傳遞到模型,這對我來說似乎不正確。

請幫忙解決這個問題

首先, 這是一個設計問題 考慮一下:“喜歡”是用戶和照片之間的某種結合。 只需大聲說:“一張照片可能會被許多用戶喜歡;一個用戶可能會喜歡許多照片”。

不清楚您的“ Like模型應該位於“ Photo模型和“ User模型之間嗎?

.----------.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM