You could add a hidden field to the form with the projects id:
<%= f.hidden_field :id, @project.id %>
Update
I think the main problem is caused by you trying to use the create action for either creating a project or updating a project. You should really only be creating a new project in the create action and use an update action to update an existing project.
You could do something like the below to make your create action work for both but it's a bit hacky:
In your view
<%= f.hidden_field(:id, @project.id) if @project.persisted? %>
In your controller
if params[:id]
@project = current_user.projects.find(params[:id])
@project.assign_attributes(project_params)
else
@project = current_user.projects.build(project_params)
end
if @project.save
...
The right way
I haven't used bootstrap_form_for but it should work that same as the normal form_for except for the field formatting.
When you do:
<%= bootstrap_form_for(@project) do |f| %>
It should automatically check if @project is persisted or not and make the form a new form if it isn't or make it a edit form if it is.
The new form will submit to the create action and the edit form should automatically insert the projects id in a hidden_field and will submit to the update action. Therefore you should be able to keep your original view code but add an update action in your controller like so:
Update action
def update
@project = current_user.projects.find(params[:id])
if @project.update_attributes(project_params)
flash[:success] = "Project updated!"
redirect_to root_url
else
flash[:success] = "Project not updated!"
redirect_to root_url
end
end
Create action
def create
@project = current_user.projects.build(project_params)
if @project.save
flash[:success] = "Project created!"
redirect_to root_url
else
flash[:success] = "Project not created!"
redirect_to root_url
end
end
You'll need to make sure you have the update route in your routes too. Probably just:
# routes.rb
resources :projects
Adding an edit form
Somewhere in your views you need to create an edit form. This is if you want to make a edit form for all of current_users's projects:
<% current_user.projects.each do |project| %>
<%= bootstrap_form_for(project) do |f| %>
... # rest of form here etc
<% end %>
<% end %>
你只提供create方法,你还能提供渲染html表单的控制器方法吗?我的意思是什么
@project
中的<%= bootstrap_form_for(@project) do |f| %>
我认为它应该是你在同一个控制器中的新方法