Rails noob here. I have a rails application with (in this example) three tables. Users, Machines, and Tests.
Users have many Machines and Tests.
Machines belong to Users.
Tests belong to Machines.
When I create a new test, I want the field test.machine_id to automatically be set to the id of the machine that owns that test. I have been able to create a field with a drop-down menu showing all machines owned by current_user, but I don’t want the user to have to set this field manually.
Tests can only be created by accessing a “create new test” link on a Machine Show page.
*For example, User 1 has Machines 4 and 5. When viewing Machine 5’s Show page, I want to create test 10. I want test(10).machine_id to be set to 5 without a user having to enter this manually.*
In my tests_controller.rb file, I have the following:
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
end
I imagine I need something like:
def create
@test = current_machine.tests.build(params[:test])
...
end
…but I don’t think current_machine is an actual object.
Tests can only be created by accessing a “create new test” link on a Machine Show page.
Any suggestions?
Consider using a nested resource for your
Testmodel. In your routes file, you would set up your resources like this:This will make the route for a new
Testlook like/machines/:machine_id/tests/new. So now your link to the new Test page would look something likeand your
newaction inTestsControllerwould be something likeFinally, the form for your nested
Testresource would be something likeThat sets up the form to post to a path that will automatically include your machine_id, something
/machines/123/tests.So in the
createaction of yourTestsControlleryou can do something like