Rails has_many:通过连接模型中的额外属性查找 [英] Rails has_many :through Find by Extra Attributes in Join Model

查看:32
本文介绍了Rails has_many:通过连接模型中的额外属性查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆