如何使用rails多态关联创建对象

时间:2017-01-09 14:39:00

标签: ruby-on-rails ruby-on-rails-4 associations polymorphic-associations

我想使用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

1 个答案:

答案 0 :(得分:2)

您尚未在任何地方定义@popular_school变量。这就是您收到NoMethodError (undefined method new for nil:NilClass):错误的原因。

尝试PopularSchool.create(your_params)