當我嘗試在控制器上運行我的功能測試一個名爲「程序」的資源,大部分我的測試導致NoMethodError:如何去實例化控制器中的子模型關聯?
NoMethodError: undefined method `programs' for nil:NilClass
該計劃的資源有一個營資源belongs_to的關係, has_many程序。從我在研究這個問題上的經驗來看,在Rails控制檯,用戶界面以及我的模型測試中都可以正常工作。
爲什麼我得到這個問題,我該如何解決它?
這裏是我使用的代碼:
的營模式
class Camp < ActiveRecord::Base
has_many :contacts
has_many :sessions
has_many :programs
has_many :parents
has_and_belongs_to_many :campers
has_one :address, :as => :addressable
accepts_nested_attributes_for :address, :allow_destroy => true
validates :name, :presence => true
validates :uri, :presence => true, :uniqueness => true
validates :email_address, :email => true, :allow_nil => true
end
的計劃模式
class Program < ActiveRecord::Base
belongs_to :camp
has_many :program_populations
has_many :sessions, :through => :program_populations
has_and_belongs_to_many :campers, :join_table => "campers_sessions_programs"
accepts_nested_attributes_for :program_populations
validates :camp, :presence => true
validates :name, :presence => true
validates :min_age, :presence => true, :numericality => {:only_integer => true}
validates :price, :presence => true, :numericality => true
end
程序控制器創建方法
def create
@camp = Camp.find_by_uri(params[:camp_id])
@program = @camp.programs.build(params[:program]) #THIS IS THE PROBLEM AREA
respond_to do |format|
if @program.save
format.html { render :text => "program created!", :status => :created }
format.xml {render :xml => @program, :status => :created, :location => @program}
else
format.html { render :action => "new", :status => :bad_request }
format.xml { render :xml => @program.errors, :status => :bad_request }
end
end
end
我的測試案例
test "should create program" do
assert_difference('Program.count') do
post :create, :program => {
:camp => camps(:bolo),
:name => "Test Program",
:min_age => 10,
:price => 100.00
}
end
assert_response :created
assert_not_nil assigns(:program)
get :show, :id => assigns(:program).to_param
assert_response :success
end
不起作用。他使用`params [:camp_id]`,它不在`params [:program]`哈希中。看到我的答案。 – vonconrad 2011-01-20 01:29:48
是的,後不久注意到(現在糾正)... – 2011-01-20 13:32:01