我今天花了很多时间试图弄清楚如何在一个多对多的表中查询它所属的表中的记录。
如果我有一个连接用户和事件的members表,什么样的查询会找到参加给定事件的所有用户,或者某个给定用户正在参加的所有事件?
我最终遇到了这样的东西(它是有效的):
User.joins(:members).where("members.event_id = ?", @event.id)
但是,这种查询可以在没有SQL语法的情况下完成吗?类似于:
Member.where(user: @user).first.events
发布于 2016-12-08 06:55:15
您应该能够访问用户的事件和事件的用户,如下所示:
@event.users
@user.events
如果您定义了has_many :通过关联(http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)
class User < ApplicationRecord
has_many :members
has_many :events, through: :members
end
class Member < ApplicationRecord
belongs_to :user
belongs_to :event
end
class Event < ApplicationRecord
has_many :members
has_many :users, through: :members
end
https://stackoverflow.com/questions/41030569
复制相似问题