繁体   English   中英

Ruby on Rails:如何在控制器函数之间传递变量?

[英]Ruby on Rails: How to pass variable between controller functions?

我需要在create函数中使用新函数中的params [:number],我将如何去做?

def new
   @test_suite_run = TestSuiteRun.new

    @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })
end

def create        
    @test_suite_run = TestSuiteRun.new(params[:test_suite_run])

    @tests = Test.find(:all, :conditions => { :test_suite_id => //I need the same params[:number] here})   
end

编辑:我想我很困惑,因为新和创建之间的区别。 我通过将参数传递给new来获取参数:number。

new_test_suite_run_path(:number => ts.id)

然后,我用它来生成表格。 我不明白该在create函数中做什么。 如果我删除了控制器中的create函数,则当我以new提交表单时,它会给我一个错误,指出控制器中没有create动作。 这是否意味着我必须将所有新功能移至create函数? 那怎么可能,我必须创建一个create.html.erb并移动所有表单信息吗?

您可以使用Flash: http//api.rubyonrails.org/classes/ActionDispatch/Flash.html

Flash提供了一种在动作之间传递临时对象的方法。 您放置在闪光灯中的任何东西都将暴露于下一个动作,然后清除。


def new
   @test_suite_run = TestSuiteRun.new
   @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })

   flash[:someval] = params[:number]
end

def create        
    @test_suite_run = TestSuiteRun.new(params[:test_suite_run])

    @tests = Test.find(:all, :conditions => { :test_suite_id => flash[:someval] })   
end

我猜我很困惑,因为new和create then之间的差异。

让我们首先解决这个问题。

new方法将为Rails生成TestSuiteRun实例的表单生成一个视图。 该实例仅在时间上存在内存。

create方法接受在表单中输入的数据,并实际上将创建的实例永久保存到数据库中。

我认为您不需要更改new方法。

尝试将您的create方法更改为此。

def create
  @test_suite_run = TestSuiteRun.new(params[:test_suite_run])
  @test_suite_run.save
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM