我对在Rails中建立关联时使用:source有疑问

问题描述 投票:0回答:1

我在rails项目中设置关联时遇到问题,想知道是否有人可以帮助我?

我有三种模型:用户,评论和事件。用户有两种:组织用户和志愿者。我在尝试使event.volunteersvolunteer.joined_events工作时遇到问题...以下是模型的设置方式:

class Comment < ApplicationRecord
    belongs_to :organization, class_name: "User"
    belongs_to :volunteer, class_name: "User"
    belongs_to :event
end
class User < ApplicationRecord
    has_many :organized_events, foreign_key: "organization_id", class_name: "Event"
    has_many :joined_events, through: :being_commented_comments, :source => :event
    has_many :commented_comments, foreign_key: "organization_id", class_name: "Comment"
    has_many :being_commented_comments, foreign_key: "volunteer_id", class_name: "Comment"
end

class Event < ApplicationRecord
    belongs_to :organization, class_name: "User"
    has_many :volunteers, through: :comments, source: "Volunteer"
    has_many :comments
end

而且我不断收到类似的错误:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError (Could not find the source association(s) "Event" in model Comment. Try 'has_many :joined_events, :through => :being_commented_comments, :source => <name>'. Is it one of organization, volunteer, or event?)

ActiveRecord::HasManyThroughOrderError (Cannot have a has_many :through association 'User#joined_events' which goes through 'User#being_commented_comments' before the through association is defined.)

而且我认为发生问题是因为我对:source不够熟悉。。。任何建议都将不胜感激!谢谢!

ruby-on-rails activerecord associations
1个回答
0
投票

使用has_many through:时,必须在间接关联之前声明要通过的关联:

class User < ApplicationRecord
  has_many :organized_events, foreign_key: "organization_id", class_name: "Event"
  has_many :being_commented_comments, foreign_key: "volunteer_id", class_name: "Comment"
  has_many :joined_events, through: :being_commented_comments, source: :event
  has_many :commented_comments, foreign_key: "organization_id", class_name: "Comment"
end
© www.soinside.com 2019 - 2024. All rights reserved.