문제

루비와 레일에 새로운 것이지만 지금은 지금까지 교육을 받았습니다.

이벤트와 사용자가 테이블 이벤트 사용자를 통해 가입 한 두 가지 모델이 있습니다.

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

이것은 "The Rails Way"와 상반되는 것 같습니다. 누구든지 나를 깨달을 수 있습니까? 오늘 밤 (오늘 아침) 오랫동안 나를 괴롭 혔습니까?

도움이 되었습니까?

해결책

이와 같은 것을 사용자 모델에 추가하는 것은 어떻습니까?

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

그 후에는 전화를 통해 사용자를위한 활성 이벤트를 얻을 수 있어야합니다.

User.first.active_events

다른 팁

밀라노 노보타는 좋은 해결책을 가지고 있지만 :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])

물론,이 조회를 많이 할 계획이라면 밀라노 노보 타가 제안한 것처럼 별도의 협회를 제공하지만 요구 사항 당신이 그렇게하는 방식으로

글쎄, 더 많은 책임이있다 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 모델 및 변경 사항은 다른 모든 모델에 반영됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top