如何创建一个对象 - 有一个:通过

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 

【讨论】:

以上是关于如何创建一个对象 - 有一个:通过的主要内容,如果未能解决你的问题,请参考以下文章

如果创建父类的数组,如何通过数组对象从子类访问方法?

获得Class类对象的几种方法

java 通过jni 向 c 传递一个 java 对象, c 如何取得这个对象的属性值?

如何知道使用的对象是spring的代理类

如何使用HttpRequest对象

如何使用 NSUserdefaults 为每个启动的对象创建一个密钥