【发布时间】:2014-06-09 08:56:28
【问题描述】:
我正在尝试将新模型添加到现有模型网格中。现有的工作完美,但我无法让新的工作正常,我想知道该协会是否能够按照我试图使其工作的方式工作。更新:正如我刚刚被问到的那样:belongs_to through 是我在解决这个问题时读到的。如果它不存在,has_one through 会是正确的方法吗?我也试过了,还是不行。
这是现有的网格:
class Course
has_many :users, through: :enrollments
has_many :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
# has fields :user_id, :course_id
end
现在用户应该能够对他已完成的课程进行评分。 (如果他有,有一个带有他的 id 和课程 id 的注册。)我认为最好这样写:
class Course
has_many :users, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class User
has_many :courses, through: :enrollments
has_many :enrollments
has_many :ratings, through: :enrollments
end
class Enrollment
belongs_to :course
belongs_to :user
has_one :rating
# has fields :user_id, :course_id
end
class Rating
belongs_to :enrollment
belongs_to :course, through: :enrollment
belongs_to :user, through: :enrollment
end
当我尝试在控制台中创建评级时,我收到以下错误:
User.first.ratings.create(text: "test", course_id: Course.first.id)
ArgumentError: Unknown key: through
更新
当我使用has_one through insted 时,出现以下错误:
ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'User#ratings' because the source reflection class 'Rating' is associated to 'Enrolment' via :has_one.
完全可以这样做吗?谢谢!
【问题讨论】:
-
belongs_to :through?真的存在吗? -
我在谷歌搜索时在某处读到它。如果不是,has_one :trough 会是正确的方法吗?我也试过了,但是没用。
-
我认为没有 belongs_to :through in rails
-
是的!也许你应该选择
has_one :through。 -
也许你应该使用
delegate。
标签: ruby-on-rails activerecord associations