class Card < ApplicationRecord
has_one :card_rating
has_one :rating, through: :card_rating
end
class Rating < ApplicationRecord
has_many :card_ratings
has_many :cards, through: :card_ratings
end
class CardRating < ApplicationRecord
belongs_to :card
belongs_to :rating
end
我想按照以下方式做点什么:
c = card.card_rating.new
c << rating
但似乎没有任何关联正在发生,因为在第一个语句中我已收到以下错误:
undefined method `new' for nil:NilClass
答案 0 :(得分:0)
对于一对多关系,您不需要连接表:
class Card
belongs_to :rating
end
class Rating
has_many :cards
end
相反,如果域规定关系是间接的,则使用has_one :through
。
class Student
belongs_to :school
has_one :headmaster, through: :school
end
class School
has_many :students
end
class Headmaster
belongs_to :school
has_many :students, through: :school
end