This is my first time to ask a question.I have a long question, but I will chew it up as much as possible, so I would appreciate it if you could let me know the details.
In my environment, when I post a new post with Rails, and when I get stuck in validation, the URL changes as follows:
ttp://localhost:3000/posts/new
↓↓↓
ttp://localhost:3000/posts
It may not be necessary, but this is what the controller expects.
def new
@post=Post.new
@post.build
end
def create
@post=current_user.posts.build(post_params)
[email protected]
redirect_to post_path, notice: 'Post was successfully created.'
else
render action: : new
end
end
I'm concerned about the URL, but when I get stuck in the validation, the contents of the form are kept, so I don't think it's a problem as long as I don't care about the URL.
However, if you return once with the browser button (ttp://localhost:3000/posts/new) and proceed again (ttp://localhost:3000/posts), the index action will be loaded as per the URL, so your entries will disappear.
If the index action is not configured, the following error occurs:
PostsController#index is missing a template for this request format and > variant.request.format: ["text/html"] request.variant: [ ] NOTE!For>XHR/Ajax or API requests, this action would normally respond with 204>Content. If you write the index action on the controller as follows, the form will appear, but the contents of the form will disappear and I feel that it is aggressive. How do Rails users handle themselves? The smart solution is I would appreciate it if anyone could tell me the solution and how they usually deal with it. I'm sorry for the amateur question.def index
@post=Post.new
@post.build
render action: : new
end
·Do not change the URL even after validation error (remain /post/new)
I think that's the quickest thing to do, but I don't know how to do it, and as long as Rails has changed the URL after the validation error, I think there's a reason (I don't know if I google it).
Thank you for your cooperation.
I was caught in the same matter...
It may be a powerful technique, but I decided to change the URL with javascript.
(There seems to be a better way...)
_form.html.erb
<%if post.errors.any?%>
<script type="text/javascript">
$(document).ready(function(){
history.pushState(',',', location.href+'/new')
});
</script>
<%end%>
© 2024 OneMinuteCode. All rights reserved.