如何创建一个对象 - 有一个:通过
Posted
技术标签:
【中文标题】如何创建一个对象 - 有一个:通过【英文标题】:How to create an object - has one :through 【发布时间】:2016-03-20 18:34:21 【问题描述】: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
【问题讨论】:
【参考方案1】:一对多关系不需要连接表:
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
【讨论】:
以上是关于如何创建一个对象 - 有一个:通过的主要内容,如果未能解决你的问题,请参考以下文章