这里是 Rails 菜鸟。我有一个 Rails 应用程序(在这个例子中)有三个表。用户、机器和测试。
用户有很多机器和测试。
机器属于用户。
测试属于机器。
当我创建一个新测试时,我希望字段 test.machine_id 自动设置为拥有该测试的机器的 ID。我已经能够创建一个带有下拉菜单的字段,显示 current_user 拥有的所有机器,但我不希望用户必须手动设置此字段。
只能通过访问机器展示页面上的“创建新测试”链接来创建测试。
*例如,用户 1 有机器 4 和 5。在查看机器 5 的显示页面时,我想创建测试 10。我希望将 test(10).machine_id 设置为 5,而无需用户手动输入.*
在我的 tests_controller.rb 文件中,我有以下内容:
def new
@test = Test.new
@machines = current_user.machiness.all
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @test }
end
end
def create
@test = Test.new(params[:test])
respond_to do |format|
if @test.save
format.html { redirect_to(@test, :notice => 'Test was successfully created.') }
format.xml { render :xml => @test, :status => :created, :location => @test }
else
format.html { render :action => "new" }
format.xml { render :xml => @test.errors, :status => :unprocessable_entity }
end
end
结束
我想我需要这样的东西:
def create
@test = current_machine.tests.build(params[:test])
...
end
...但我不认为 current_machine 是一个实际的对象。
只能通过访问机器展示页面上的“创建新测试”链接来创建测试。
有什么建议吗?
最佳答案
考虑为您的测试
模型使用嵌套资源。在您的路由文件中,您可以像这样设置您的资源:
resources :machines do
resources :tests
end
这将使新的 Test
的路由看起来像 /machines/:machine_id/tests/new
。所以现在您到新测试页面的链接看起来像
<%= link_to "New Test", new_machine_tests_path(@machine) %>
TestsController
中的new
操作类似于
def new
@test = Test.new
@machine = Machine.find(params[:machine_id])
...
end
最后,嵌套的 Test
资源的形式类似于
<%= form_for [@machine, @test] do |f| %>
...
这会将表单设置为发布到一个路径,该路径将自动包含您的 machine_id,例如 /machines/123/tests
。
因此,在 TestsController
的 create
操作中,您可以执行以下操作
def create
@test = Test.new(params[:test])
@test.machine_id = params[:machine_id]
...
end
关于ruby - 在 Rails 中创建新记录时如何自动设置字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956777/