How to use js.erb views in Rails 6

吃可爱长大的小学妹 提交于 2021-02-05 06:21:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!