问题
Is there possibility to use js.erb
views in Rails 6 application? I get
MyController#my_action is missing a template for this request format and variant.
request.formats: ["text/html"]
request.variant: []
error for actions using js.erb
views after migration to rails 6.
In my action I just assign value to instance variable:
def next_question
@lesson = lesson
end
In routes I have
put ':package_id/lessons/next_question', to: 'lessons#next_question', as: 'next_question'
And there is form for submit this request
= form_tag next_question_path(@package), method: :put, remote: true
If I create (for test) html.slim
file, everything works well.
If I add format.js
to controller, I get ActionController::UnknownFormat
回答1:
Create a view file next_question.js.erb
, then do this
def next_question
@lesson = lesson
respond_to do |format|
format.js
end
end
Also, enable ujs
in application.js
file, add this line
require("@rails/ujs").start()
Give it a try!
回答2:
In rails controller method you need to define the format of the requests the method can respond to by adding a respond_to block in the method. If there is no respond_to block present then by default the method only respond to html requests. For js or any other request you need to add a respond_to block.
def next_question
@lesson = lesson
respond_to do |format|
format.js
end
end
this will tell the method that it needs to look for a js.erb file named next_question.js.erb, you can also specify the file name like this format.js { render partial: 'filename' }
and then the method will look for and respond with filename.js.erb
file.
来源:https://stackoverflow.com/questions/60900787/how-to-use-js-erb-views-in-rails-6