我有两个具有多对多关系的模型(model1
和model2
)。已存在的表只包含每个模型的主键。 has_many through
关系在各自的模型中设置。但是,当我在POST中尝试以下内容时,我会得到经典的
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array. The error occurred while
evaluating nil.[]":
model1 = Model1.find(params[:id])
model2 = Model2.find(params[:model2_id])
model1.model2s << model2
model1
不是零。 model1.model2s
不是零。 model2
不是零。这个错误来自哪里?
答案 0 :(得分:1)
如果您的联接表仅包含每个模型的主键,那么您希望has_and_belongs_to_many
不是has_many :through