0
我正在尝试编写一个允许用户注册事件的应用程序。每个活动的主人和用户都计划参加活动。我无法为后者选择正确的关联。我尝试过has_and_belongs_to_many,但是在某处不推荐使用它,所以我试着用has_many:through,它似乎不起作用。这是我想出了现在:我应该使用哪个Rails Association?
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
此代码返回一个错误:
Cannot modify association 'Event#users' because the source reflection class 'User' is associated to 'EventUser' via :has_many.
你们可以告诉我我做错了什么,怎么做对不对?这是我第一个认真的Rails应用程序,我真的想以正确的方式编写它。提前致谢。