我想使用Polymorphic关联创建对象,但它返回错误,如:
NoMethodError (undefined method `new' for nil:NilClass):
以下是params:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"TAQdqSTXAFCrq6yZBUnjVXe7IsPqmxuLh/qM/2QvKaVvsfP
/Sy6VNF7H38IzOg8aMj39t6HR+aZLLtyj8uMzyw==", "search"=>"Newport-Mesa Unified
School District", "id"=>"32", "type"=>"PrivateSchool", "commit"=>"Submit"}
以下是模特:
class PrivateSchool < ActiveRecord::Base
has_many :popular_schools, as: :resource, :dependent => :destroy
end
class PopularSchool < ActiveRecord::Base
belongs_to :resource, polymorphic: true
end
class School < ActiveRecord::Base
has_many :popular_schools, as: :resource, :dependent => :destroy
end
控制器代码:
def index
@popular_school = PopularSchool.new
@popular_schools = PopularSchool.all
end
def create
@popular_school.new.save
respond_to do |format|
format.html { redirect_to root_path }
format.json { head :no_content }
format.js
end
end
答案 0 :(得分:2)
您尚未在任何地方定义@popular_school
变量。这就是您收到NoMethodError (undefined method new for nil:NilClass):
错误的原因。
尝试PopularSchool.create(your_params)