0

I have controller Message_Controller and this Controller has method "message" in this method i wanna render .js.erb file i need call js function from rails controller.I need reneder it without html-template(layout) just only js-code in this code i will call js-function with args .How to make it ??

My routes:

 post 'chat_bot/message', to: 'chat_bot#message'

My controller:

class ChatBotController < ApplicationController
     layout false

    def message
         #gon.watch.message = params[:text]
        @message = params[:text]
            puts @message
        render partial: 'message.js.erb', layout: false
    end


end

my message.js.erb file

alert('<%=@message %>');

2 Answers 2

1

With

render partial: 'message.js.erb', layout: false

Rails is going to look for a partial called _message.js.erb right in the folder responding to that controller.

You can use respond_to and there specify the format and what to render:

def message
  respond_to do |format|
    format.html { render partial: 'message.js.erb' }
  end
end

You can skip the instance variable assignation if you prefer, as you have access to the params within the request.

If your idea is to "evaluate" the alert, then it still should be inside a script tag:

<script>
  alert("<%= params[:text] %>");
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Hi thx. It works. But when i use render then open new page "/chat_bot/message". How to call a function from the controller without opening a new page?
You can make a JSON request.
0

just update it with

def message
  @message = params[:text]
  respond_to do |format|
     format.js
  end
end

2 Comments

How to call a function from the controller without opening a new page?
make a ajax call with dataType: "script"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.