Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use js.erb views in Rails 6

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

like image 570
krzyskk Avatar asked Nov 02 '25 14:11

krzyskk


2 Answers

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!

like image 159
Rajdeep Singh Avatar answered Nov 04 '25 06:11

Rajdeep Singh


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.

like image 31
Abdul Rehman Avatar answered Nov 04 '25 06:11

Abdul Rehman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!