I have two forms in my new view, one is for the product and the other is for fotos. When I upload the fotos with a select.file field, these are created by Ajax call by a file create.js.erb then when I fill the others fields to the product I've another button to create it. So I have two forms and one way to create each one.
The problem is the ID, the solution that I've found was to create an object before the user enter to the new view, so I have this code:
Product's controller:
def new
@product = current_user.products.create
end
It creates an object nil, now I can create my Foto to that object, like this:
Painting's controller:
def create
@product = Product.last
@painting = @product.paintings.create(params[:painting])
end
The problem is the line "@product = Product.last", I know that it isn't the right solution, because when I try the edit action, and when I try to create new objects it goes to the last product and not to the actual edit product.
How can I find that current product at my new action???
Thanks a lot.
Building a new object (really showing the new form, since #new is a GET request and should not make destructive changes)
def new
@product = current_user.products.build
end
Creating a new object
def create
@product = current_user.products.build(params[:product])
if @product.save
redirect_to @product
else
render :new
end
end
Showing the Edit form for an object
def edit
@product = current_user.products.find(params[:id])
end
Updating an existing product
def update
@product = current_user.products.find(params[:id])
if @product.update_attributes(params[:product])
redirect_to @product
else
render :edit
end
end
You'll notice that the GET requests (new and edit) make no chagnes to the database.
The two destructive requests (PUT and POST) to (update/create) make changes to the database.
What you are doing in general is awkward and probably not the best way to use the new action of a controller.
To answer your question you would need to pass in the ID of the product in your parameters.
Depending how you are submitting your paintings form you need to add the parameter in either the body of the request or the url. that way you would be able to do something like
Painting's controller
def create
@product = Product.find(params[:product_id]
@painting = @product.paintings.create(params[:painting])
end
If you add a code snippet of your views/forms I'll probably be able to help you better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.