我应该使用哪个 Rails 协会?
Which Rails Association should I use?
我正在尝试编写一个允许用户注册活动的应用程序。每个活动都有其所有者和计划参加该活动的用户。我无法为后者选择正确的关联。我试过 has_and_belongs_to_many,但在某处读到不建议使用它,所以我尝试使用 has_many :through 但它似乎不起作用。这是我现在想到的:
class User < ApplicationRecord
has_secure_password
has_many :events, :foreign_key => :owner_id
has_many :event_users
has_many :events, :through => :event_users
end
class Event < ApplicationRecord
belongs_to :user, :foreign_key => :owner_id
has_many :event_users
has_many :users, :through => :event_users
end
class EventUser < ApplicationRecord
has_many :users
has_many :events
end
注册码如下所示:
def sign_up
user = User.find(session[:user_id])
@event.users << user
end
这段代码returns一个错误:
Cannot modify association 'Event#users' because the source reflection class 'User' is associated to 'EventUser' via :has_many.
你们能告诉我我做错了什么以及如何做对吗?这是我第一个认真的 Rails 应用程序,我真的很想以正确的方式编写它。提前致谢。
您可能想区分主人和客人。我会这样做:
#models/event.rb
belongs_to :owner, class_name: "User"
has_many :guests, class_name: "User", through: :event_users
has_many :event_users
#models/eventuser.rb
belongs_to :users
belongs_to :events
#models/user.rb
has_many :event_users
has_many :events, through: :event_users
has_many :event_ownerships, class_name: "Event"
这里非常重要的一点是 EventUserbelongs_to 具有您指定的多对多关系。
此外,您不能重新定义 user.events 关联,您需要重命名它。
我正在尝试编写一个允许用户注册活动的应用程序。每个活动都有其所有者和计划参加该活动的用户。我无法为后者选择正确的关联。我试过 has_and_belongs_to_many,但在某处读到不建议使用它,所以我尝试使用 has_many :through 但它似乎不起作用。这是我现在想到的:
class User < ApplicationRecord
has_secure_password
has_many :events, :foreign_key => :owner_id
has_many :event_users
has_many :events, :through => :event_users
end
class Event < ApplicationRecord
belongs_to :user, :foreign_key => :owner_id
has_many :event_users
has_many :users, :through => :event_users
end
class EventUser < ApplicationRecord
has_many :users
has_many :events
end
注册码如下所示:
def sign_up
user = User.find(session[:user_id])
@event.users << user
end
这段代码returns一个错误:
Cannot modify association 'Event#users' because the source reflection class 'User' is associated to 'EventUser' via :has_many.
你们能告诉我我做错了什么以及如何做对吗?这是我第一个认真的 Rails 应用程序,我真的很想以正确的方式编写它。提前致谢。
您可能想区分主人和客人。我会这样做:
#models/event.rb
belongs_to :owner, class_name: "User"
has_many :guests, class_name: "User", through: :event_users
has_many :event_users
#models/eventuser.rb
belongs_to :users
belongs_to :events
#models/user.rb
has_many :event_users
has_many :events, through: :event_users
has_many :event_ownerships, class_name: "Event"
这里非常重要的一点是 EventUserbelongs_to 具有您指定的多对多关系。
此外,您不能重新定义 user.events 关联,您需要重命名它。