Ruby on rails 3 Rails:从模型中的has\u many:through关系中提取值
我想要的是Ruby on rails 3 Rails:从模型中的has\u many:through关系中提取值,ruby-on-rails-3,associations,has-many-through,Ruby On Rails 3,Associations,Has Many Through,我想要的是User上的一个方法,我可以查询该方法以了解该用户在给定事件中的状态。比如: User has_many :reservations, :dependent => :destroy has_many :events, :through => :reservations Reservation belongs_to :user belongs_to :event Event has_many :reservations, :dependent =
User
上的一个方法,我可以查询该方法以了解该用户在给定事件中的状态。比如:
User
has_many :reservations, :dependent => :destroy
has_many :events, :through => :reservations
Reservation
belongs_to :user
belongs_to :event
Event
has_many :reservations, :dependent => :destroy
has_many :attendees, :through => :reservations, :source => :user
我对关联语法感到困惑,尤其是…列保留.event不存在
对于任何特定事件,每个用户只能有一个预订…首先
假设是这样的。(更好的方式?)
无论如何,预订
模型上的状态
方法应返回%w[未出席、等待付款、已收到付款]
处理模型之间的关系/查找的“Rails方式”是什么(甚至可以从更清晰的方法名称开始:
attender\u status(event)
) User.reservations
是一个集合,User.events
是一个集合。因为您的直通关联是通过所属的
链接的,所以两个集合的大小相同(假设所有预订都有一个事件)
User.reservations.event
不存在,但User.reservations.first.event
将存在(假设至少有一个预订)
第一个调用是类上的函数Reservation::event
,第二个调用是类实例上的Reservation\event
。对集合调用Reservation::first
,将返回一个实例
我想你只需要像这样修正这条线:
def attendee_status(event)
res = self.reservations.where(event: event.id).first
if res
res.status
else
0
end
end
我希望这有帮助
res = self.reservations.where(event_id: event.id)