我将 :number 作为参数传入,然后将其分配给before_filter
.
在new
控制器中的函数中,我使用变量@test_suite_num 来过滤一个名为的表Test
,以获取其id 匹配@test_suite_num 的条目数。我使用这个计数来生成适当数量的子资源test_run
。
我也这样做,create
但由于某种原因,每当我在依赖于@test_suite_num
. 我假设由于 create 从不接受参数,因此变量永远不会被初始化。如何在create
函数中使用@test_suite_num?
控制器代码:
before_filter :get_number, :only => [:new, :create]
def get_number
@test_suite_num = params[:number]
end
新的
def new
@test_suite_run = TestSuiteRun.new
@tests = Test.find(:all, :conditions => { :test_suite_id => @test_suite_num })
@tests.count.times do test_run = @test_suite_run.test_runs.build end
end
创造
def create
@test_suite_run = TestSuiteRun.new(params[:test_suite_run])
@tests = Test.find(:all, :conditions => { :test_suite_id => @test_suite_num })
@tests.count.times do test_run = @test_suite_run.test_runs.build(params[:test_suite_run]) end
if @test_suite_run.save
flash[:success] = "Run Added Succesfully"
redirect_to test_suite_runs_path(@test_suite_run)
else
render 'new'
end
end
编辑:
我刚开始使用 RoR,所以我的风格真的很乱。但是我的问题仍然存在。我的问题是,在我的表单中,我使用的是@tests,它是用我传入的参数初始化的。我可以很好地查看表单,但是当我点击提交时,我得到:
Showing /Users/vsp/Documents/rails_projects/web_db/app/views/test_suite_runs/_form.html.erb where line #13 raised:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Extracted source (around line #13):
10:
11: <%= f.fields_for :test_runs do |builder| %>
12:
13: Test <%= @tests[@i].id %><br><br>
14:
15: <%= render "partial", :f => builder %>
16: <hr>
显然,这意味着创建控制器没有得到 params[:number],因此表单提交中断。我的创建功能有什么问题吗?
参数:{"utf8"=>"✓", "authenticity_token"=>"/vbOcFozTEAvoa03OUBfyxJbJ9AQp8m8yA04LkxlRE8=", "test_suite_run"=>{"test_runs_attributes"=>{"0"=>{"test_id"=>"1", "machine_id"=>"", "date"=>"2012-07-09 15:59:53 -0700", "status"=>"", "result"=>""}, "1"=> {"test_id"=>"3", "machine_id"=>"", "date"=>"2012-07-09 15:59:53 -0700", "status"=>"", "result"= >""}, "2"=>{"test_id"=>"6", "machine_id"=>"", "date"=>"2012-07-09 15:59:53 -0700", "status "=>"", "结果"=>""}, "3"=>{"test_id"=>"7", "machine_id"=>"", "date"=>"2012-07-09 15:59: 53 -0700", "状态"=>"", "结果"=>""}}, "日期"=>"2012-07-09 15:59:53 -0700"}, "提交"=>"提交”,“动作”=>“创建”,“控制器”=>“test_suite_runs”}"提交", "操作"=>"创建", "控制器"=>"test_suite_runs"}"提交", "操作"=>"创建", "控制器"=>"test_suite_runs"}
通过这个,它只是我表单中的所有 text_input 字段。