Rails 7 ActionController::UnknownFormat in CommentsController#create respond_to - javascript

I have a comments controller that i want to load a partial "create.js.erb"
class CommentsController < ApplicationController
skip_before_action :verify_authenticity_token
def create
#comment = Comment.new(comment_params)
#comment.account_id = current_account.id
respond_to do |format|
if #comment.save
#comments = Comment.where(post_id: #comment.post_id)
format.js { render "comments/create" }
else
# unable to save
end
end
end
def comment_params
params.require(:comment).permit(:message, :post_id)
end
end
My create.js.erb partial
console.log("comment created...");
$("#post-comments").html("<%= escape_javascript(render partial: 'posts/comments', locals: { comments: #comments }) %>");
If i refresh the page the comment gets posted however when i click the submit button it send me the error ActionController::UnknownFormat in CommentsController#create
In laymans terms i want the create function to hit without having to redirect.

Seems like using Hotwire and Turbo is the way to go
respond_to do |format|
if #comment.save
#comments = Comment.where(post_id: #comment.post_id)
format.html { redirect_to posts_path }
format.turbo_stream
end
end
then you need to change create.js.erb to create.turbo_stream.erb
<%= turbo_stream.prepend "comments", #comments %>
all works as intended now
Rails 7 removes the previous way of using format.js in Rails UJS and now it's all hotwire/turbo. Kinda confusing but once you learn it no more writing javascript. :)

Related

Pass local variable to create.js.erb for an iteration in an iteration

I have a Post and a Comment model, while a post can have multiple comments and a comment belongs to a post (and a user).
I am iterating through all Posts by doing #posts.each do |d|, which is not a big deal. Also i am iterating through all the comments of a Post by d.comments.each do |comment|. No big deal too.
Ive setted up a create.js.erb to make my app a bit more dynamic and to instantly display the comment you created under a post. While my form is working fine, i have troubles setting up the create.js.erb which is giving me a NameError - undefined local variable or method 'comment' for #<Class:> Did you mean? #comment: when submitting the forms content. After reloading the page the comment is added up, but i would like to have an instant update like a single page app would behave. i have never worked with ajax before.
I would be able to solve the whole situation if i would just display the comments on a separate posts#show view but since i am iterating through every post on the index page and want to display every comment of every post and also update the comments async i just cant figure out how to do that.
How do I create the desired behavior?
Sorry if my question is asked kinda wonky.
comments_controller.rb
def create
#user = current_user
#comment = Comment.new(comment_params)
#comment.user_id = #user.id
respond_to do |format|
if #comment.save
format.js {}
format.html { redirect_to root_path, notice: 'Comment added' }
format.json { render :show, status: :created, location: #comment }
else
format.html { redirect_to root_path }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
posts/index.html.erb
<% #posts.each do |d| %>
<%= d.content %>
<div class="comment-list">
<%= render partial: "comments/comment", collection: d.comments %>
</div>
<% end %>
comments/_comment.html.erb
<%# d.comments.reverse.each do |comment| %>
<%= comment.content %>
<%# end %>
create.js.erb
$(".comment-list").append("<%= j render partial: "comments/comment" %>");
$(".comment-list").append("<%= j render partial: "comments/comment" %>");
Replace above code with
$(".comment-list").append("<%= j render partial: "comments/comment", locals: {comment: #comment} %>");

ParksController#create is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

I'm creating a park with a modal. Everything seems to work fine when I'm not saving a picture in the form. When I do add a picture and try to create/save, the picture gets saved, but I get an error message saying:
ParksController#create is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []
"\nrequest.variant: #{request.variant.inspect}"
raise ActionController::UnknownFormat, message
elsif interactive_browser_request?
message = "#{self.class.name}\##{action_name} is missing a template " \
"for this request format and variant.\n\n" \
I'm overlooking something, but don't see what.
controller
class ParksController < ApplicationController
skip_before_action :verify_authenticity_token
after_action :verify_authorized
def new
#park = current_user.parks.build
respond_to do |format|
# format.html { redirect_to root_url, alert: 'Page not accessible' }
format.html
format.js
end
authorize #park
end
def create
#park = current_user.parks.create(park_params)
authorize #park
respond_to do |format|
if #park.save
format.js
format.html
# end
else
format.js{render 'new'}
end
end
end
You're not redirecting to another view after the create action. You're responding to html there, but not doing anything with it. Usually after a create, the user is redirected to the index view. I think if you passed a block to the html response and redirected, the error would resolve itself.
ie:
...
respond_to :html { redirect_to index_path }
...
Also, you have your end commented out for your if #park.save

respond_to do |format| gives "UnknownFormat in UsersController#show" in rails 5 app

In my rails 5 app I want to render partials in a div in the views/users/show.html.erb on link click.
I believe I have set things up accordingly but rails gives me this error ActionController::UnknownFormat in UsersController#show
ActionController::UnknownFormat
respond_to do |format|
format.js { render :show_kwst }
end
I'm kind of lost here, I've done similar things in rail 4 by using bootstrap tabs with out any problems.
I've also added the 'responders' gem to the gemfile
This is my views/users/show.html.erb
<%= link_to 'Kwst', user_path%>
<div id="content"></div>
This is my users_controller.rb
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
#user_posts = #user.posts
#user_kwsts = #user.kwsts
respond_to do |format|
format.js { render :show_kwst }
end
end
end
And here is the `views/users/show_kwst.js.erb``
$("#content").html("<%=escape_javascript(render :partial=>"shared/show_kwst")%>");
Am I missing something?
Try to the following order, you can follow this Rails Guide About format.js
respond_to do |format|
format.html { #user_kwsts }
format.js
end
Notice the format.js in the respond_to block; that allows the controller to respond to your Ajax request. You then have a corresponding app/views/users/show_kwst.js.erb view file that generates the actual JavaScript code that will be sent and executed on the client side.

JS is not executing rails

I try to display a view in a modal but i dont know why my JS is not executing, i saw similar questions about it but it doesnt solve my issue,
My link
def create
document = Document.find(params[:document_id])
order = Order.create!(doc_sku: document.doc_sku, amount: document.price, state: 'pending')
redirect_to new_order_payment_path(order, format: :js, remote: true)
end
controller:
def new
#document = Document.last
respond_to do |format|
format.js {render layout: false, content_type: 'text/javascript'}
end
end
new.js.erb
$("#newModal .modal-content").html('<%= j render "payments/form" %>');
$("#newModal").modal();
I test it with a simple alert but nothing change
In my log
Processing by PaymentsController#new as JS
Parameters: {"remote"=>"true", "order_id"=>"35"}
I dont have warnings/errors in the network or console of my browser
Content type is wrong. Change render to just.
respond_to do |format|
format.js
end
Should work.

Rails - adding ajax to partials, 'undefined method `render''

I have a form partial, within a div with id "chapcomments", with a submit tag -
<%= f.submit "Post", remote: true %>
In the correct view folder, I have create.js.erb -
$('#chapcomments').html("<%=j render 'shared/chap_comment_complete' %>");
And in the controller I have the format block which includes
def create
#chap_comment = current_user.chap_comments.build(chap_comment_params)
respond_to do |format|
if #chap_comment.save
format.js
format.html {redirect_to chapter_path(#chap_comment.chapter)}
else
format.html { render :new }
format.json { render json: #chap_comment.errors, status: :unprocessable_entity }
end
end
end
...but I'm not getting ajax behaviour...
Where am I going wrong?
You've made the change so that the JS is in the right js.erb file in the view, but you need to move the remote: true part from the submit tag into your form_for declaration, otherwise the format.html response block will be rendered instead of format.js.

Categories

Resources