【问题标题】: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

【问题讨论】:

    标签: ruby-on-rails associations ruby-on-rails-5


    【解决方案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 
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多