Rails mongoid - 访问用户 user_id 存在于另一个 table
Rails mongoid - Access User with user_id present in another table
我有一个用户很多的应用,可以创建很多旅行,他们可以邀请朋友参与旅行。
以下是模型:
class Travel
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
embeds_many :participants
accepts_nested_attributes_for :participants
end
class Participant
include Mongoid::Document
include Mongoid::Timestamps
# relations
embedded_in :travel, :inverse_of => :participants
end
当我查看我的数据库时,我为参与者提供了以下结果:
嵌入旅行。
现在,我想访问用户,感谢您在数据库中看到的 user_id,在旅行页面上,但我不知道我必须写什么请求来实现它。我想访问作为参与者的用户。
我是否必须使用 .where()
,例如:User.where(:id.in => ...)
或 .find_by()
..?
由于Travel
和User
有关联(belongs_to
),可以直接调用..
Travel.last.user
或者
User.where(id: Travel.participants.pluck(:user_id))
我有一个用户很多的应用,可以创建很多旅行,他们可以邀请朋友参与旅行。
以下是模型:
class Travel
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
embeds_many :participants
accepts_nested_attributes_for :participants
end
class Participant
include Mongoid::Document
include Mongoid::Timestamps
# relations
embedded_in :travel, :inverse_of => :participants
end
当我查看我的数据库时,我为参与者提供了以下结果:
嵌入旅行。 现在,我想访问用户,感谢您在数据库中看到的 user_id,在旅行页面上,但我不知道我必须写什么请求来实现它。我想访问作为参与者的用户。
我是否必须使用 .where()
,例如:User.where(:id.in => ...)
或 .find_by()
..?
由于Travel
和User
有关联(belongs_to
),可以直接调用..
Travel.last.user
或者
User.where(id: Travel.participants.pluck(:user_id))