I have a Document model and I'm looking to create a Document by clicking a button that send some params from my index page. I want to do this whithout passed in the 'new' page.
What I want to do exactly is : I click the button, that create my model with params passed, then redirect to the edit page to custom this document
In my index view I use this button : <%= button_to "Edit", {:controller => "documents", :action => "create", :name=>"doc_name", :user_id=> current_user.id}, :method=>:post%>
And in my document_controller I have this :
def create
@document = Document.new(document_params{params[:user_id]})
respond_to do |format|
if @document.save
flash.now[:notice] = "Document créé avec succès."
format.turbo_stream do
render turbo_stream: [turbo_stream.append("documents", partial:"documents/document", locals: {document: @document}),
turbo_stream.update("content-d", partial:"documents/table"),
turbo_stream.replace("notice", partial: "layouts/flash")]
end
format.html { redirect_to document_path(@document), notice: "Document was successfully created." }
format.json { render :show, status: :created, location: @document }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
def document_params
params.fetch(:document, {}).permit(:doc_type, :number, :name, :total_ttc, :user_id)
end
Is there someone who can guide me to do this ?
Thank you all
UPDATE
I just change my button_to for this one :
<%= button_to "Edite", {:controller => "documents", :action => "create", :document=>{:name=>"doc_name", :user_id=> current_user.id}}, :method=>:post, class:"btn-primary" %>
If I understand you correctly, you want to:
If you never need to land on
DocumentsController#new, then you can just have the final action ofDocumentsController#newbe toredirect_toDocumentsController#editfor thatdocument.If you want to preserve the normal role of
DocumentsController#new, just create a new route and controller action, e.g.DocumentsController#create_from_indexThen you can have a form (with a submit button) on your Index page that POSTs to your new route.
Using a form is your easiest method. If you don't want to use a form, you'll need to AJAX the button data to a controller action, which is a bit more complicated (but still very doable)
For example: