簡體   English   中英

Rails has_many:通過在聯接模型中按附加屬性查找

[英]Rails has_many :through Find by Extra Attributes in Join Model

對於Ruby和Rails來說都是新手,但是我現在受過教育(這顯然沒有任何意義,哈哈)。

我有兩個模型,事件和用戶通過表EventUser加入

class User < ActiveRecord::Base
  has_many :event_users
  has_many :events, :through => :event_users
end

class EventUser < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

  #For clarity's sake, EventUser also has a boolean column "active", among others
end

class Event < ActiveRecord::Base
  has_many :event_users
  has_many :users, :through => :event_users
end

這個項目是一個日歷,我必須在其中跟蹤人們注冊並為給定事件划掉他們的名字。 我認為多對多是個好方法,但是我不能做這樣的事情:

u = User.find :first
active_events = u.events.find_by_active(true)

因為事件實際上並沒有多余的數據,所以EventUser模型可以。 雖然我可以做:

u = User.find :first
active_events = []
u.event_users.find_by_active(true).do |eu|
  active_events << eu.event
end

這似乎與“鐵軌方式”背道而馳。 誰能啟發我,這已經困擾了我今晚(今早)很長時間了?

如何在用戶模型中添加類似內容?

has_many  :active_events, :through => :event_users, 
          :class_name => "Event", 
          :source => :event, 
          :conditions => ['event_users.active = ?',true]

之后,您只需調用以下命令就可以獲取用戶的活動事件:

User.first.active_events

米蘭Novota有一個很好的解決方案-但是:conditions現在已經過時和:conditions => ['event_users.active = ?',true]位只是似乎並不十分軌反正。 我喜歡這樣的東西:

has_many :event_users
has_many :active_event_users, -> { where active: true }, class_name: 'EventUser'
has_many :active_events, :through => :active_event_users, class_name: 'Event', :source => :event

之后,您仍然可以通過調用以下命令來獲取用戶的活動事件:

User.first.active_events

即使您的u.events沒有顯式調用user_events表,由於必要的聯接,該表仍隱式包含在SQL中。 因此,您仍然可以在查找條件中使用該表:

u.events.find(:all, :conditions => ["user_events.active = ?", true])

當然,如果你打算做這個查找了很多話,當然,給它一個獨立的關聯作為米蘭Novota建議,但沒有要求為你這樣做的

好了,更多的責任被放在User模型比實際需要,並沒有充分的理由這樣做。

我們首先可以在EventUser模型中定義范圍,因為它實際上屬於哪個范圍,例如:

class EventUser < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

  scope :active,   -> { where(active: true)  }
  scope :inactive, -> { where(active: false) } 
end

現在,用戶可以同時具有兩種事件:活動事件和非活動事件,因此我們可以在User模型中定義關系,如下所示:

class User < ActiveRecord::Base
  has_many :active_event_users,   -> { active },   class_name: "EventUser"
  has_many :inactive_event_users, -> { inactive }, class_name: "EventUser"

  has_many :inactive_events, through: :inactive_event_user,
                             class_name: "Event",
                             source: :event
  has_many :active_events,   through: :active_event_users,
                             class_name: "Event",
                             source: :event
end

該技術的EventUser ,處於活動狀態或非活動狀態的功能都屬於EventUser模型,如果將來需要對其進行修改,則只能在一個地方進行修改: EventUser模型,並且將進行更改反映在所有其他模型中。

暫無
暫無

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

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