gpt4 book ai didi

ruby-on-rails - 从 :through Association 查询

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:19 25 4
gpt4 key购买 nike

我正在创建一个 Rails 应用程序来学习 has_many:通过关联...我知道我没有遵循 Rails 约定,但那是因为我想了解 Active Record 必须提供的所有不同选项。

我的问题是,我想我已经创建了关系,但我不知道如何构建邀请并查询它们以获得与会者和 attended_events。我必须先创建邀请吗?如果是这样,我如何将它与事件相关联?那么,如何才能让很多用户参加事件呢?这些问题对你们中的一些人来说可能是显而易见的,但我却难以理解。有没有人愿意给我一个基本的了解?我是否正确设置了我的代码以获得我想要的结果?到目前为止,这是我的设置:

class Invite < ActiveRecord::Base
belongs_to :attending_guest, :class_name => "User"
belongs_to :attending_event, :class_name => "Event"
end

class User < ActiveRecord::Base
has_many :created_events, :foreign_key => "creator_id", :class_name => "Event"
has_many :invites, :foreign_key => :attending_guest_id
has_many :attended_events, through: :invites, source: :attending_event
end

class Event < ActiveRecord::Base
belongs_to :creator, :class_name => "User"
has_many :invites, :foreign_key => :attending_event_id
has_many :attendees, :through => :invites, :source => :attending_guest
end

基本上,一个事件有一个创建者,我想我已经正确地完成了这部分。接下来,我希望能够获得参加该事件的用户列表。另外,我希望能够看到用户将要参加的事件。但是我什至如何构建一个邀请并让一个事件与一群用户相关联,rails 是如何处理这个的?如果有人可以解释我如何去做这些事情并给我一些说明/提示,我将不胜感激。谢谢!

最佳答案

使用 belongs_to , has_many etc. 提供了一些非常方便的方法来将对象相互关联起来。例如belongs_to附带:

 1. association
2. association=(associate)
3. build_association(attributes = {})
4. create_association(attributes = {})
5. create_association!(attributes = {})

到目前为止,您的问题是如何构建邀请并将它们与事件和用户相关联,这是我的建议:

自模型 Invite您使用 belongs_to 定义了 2 个关联, 你可以使用方法 No.5以上列表如下:

invite = Invite.create!
invite.create_attending_guest!(<the necessary attributes and respective values for creating a new user>)
invite.create_attending_event!(<the necessary attributes and respective values for creating a new event>)

或者反过来:

guest = User.create!(<attrs>)
event = Event.create!(<attrs>)
invite = Invite.create!(attending_guest: guest, attending_event: event)

I want to be able to see what events a user is going to

您可以像这样访问它们:

u = User.find(5)
events = u.attended_events

how do I have one event be associated with a bunch of users

在这种情况下,您可以使用方法 <<添加者 has_many (其他请参见 here):

u1 = User.create!(<attrs>)
u2 = User.create!(<attrs>)
u3 = User.create!(<attrs>)
event = Event.create!(<attrs>)
event.attendees << u1
event.attendees << u2
event.attendees << u3

关于ruby-on-rails - 从 :through Association 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com