i have partial form on my rails project. this form is for nested route(post and comment), and this form only brings me to make new data. the url to edit page works well, but when i get into that edit page, form tag was written like -> posts/1/comment (method: post), which makes me can not update data. my expecting result is -> posts/1/comment/1 (method: put)
form for nested route->
<%= form_with model: [post, post.comments.build] do |f| %>
<div >
<%= f.hidden_field :post_id %>
<%= f.label :content %>
<%= f.text_field :content %>
<% post.comments.build.errors.full_messages_for(:content).each do |error_message| %>
<div >
<%= error_message %>
</div>
<% end %>
<%= f.submit %>
</div>
<% end %>
edit page->
<%= render partial: "form", locals: { post: @post } %>
on controller (testing for update method works well, so i did not write it. only the problem is form tag build as post method all time.)
def edit
@post = Post.find(params[:post_id])
end
this edit form link is in post's show page, and i written @post in postcontroller
def show
@post = Post.find(params[:id])
end
routes
resources :posts do
resources :comments
end
how can i solve it?
partial form build as -> posts/1/comment (method: post) my expecting result is -> posts/1/comment/1 (method: put)
i tried change variable for glocal variable, change form for not nested(it works but i thought using nested route is right for this situation)
CodePudding user response:
I think your error is here:
<%= form_with model: [post, post.comments.build] do |f| %>
In post.comments.build
you're always initiating a new comment, therefore creating a form to create a new comment (POST), that isn't going to update anything because it doesn't exist yet. Not 100% sure about the logic of your app, but if you want a form to edit each one of the post comments (PUT), you will need to do something like:
<% post.comments.each do |comment| %>
<%= form_with model: [post, comment] do |f| %>
<% #.....
worst case scenario, you could also set manually the attributes of your form, like:
<%= form_with(model: comment, url: edit_post_comment_path(post, comment), method: "put") %>