Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

ruby - Rails has_many :through Find by Extra Attributes in Join Model

New to both Ruby and Rails but I'm book educated by now (which apparently means nothing, haha).

I've got two models, Event and User joined through a table 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

This project is a calendar, in which I have to keep track of people signing up and scratching their name out for a given event. I figure the many to many is a good approach, but I can't do something like this:

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

Because events don't actually HAVE that extra data, the EventUser model does. And while I could do:

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

This seems to be contrary to "the rails way". Can anyone enlighten me, this has been bugging me for a long time tonight (this morning)?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about adding something like this into your User model?

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

After that you should be able to get active events for a user just by calling:

User.first.active_events

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...