Rails has_many:通过在联接模型中按附加属性查找 [英] Rails has_many :through Find by Extra Attributes in Join Model
问题描述
对于Ruby和Rails来说都是新手,但是我现在受过教育(这显然意味着什么,哈哈).
New to both Ruby and Rails but I'm book educated by now (which apparently means nothing, haha).
我有两个模型,Event和User通过表EventUser联接起来
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)
因为事件实际上并没有多余的数据,所以EventUser模型会这样做.虽然我可以做到:
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)?
推荐答案
如何在用户模型中添加类似内容?
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
这篇关于Rails has_many:通过在联接模型中按附加属性查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!