Rails ajax form send message

I am creating my first application for rails and a beginner in ruby ​​and rails. I am trying to make a submit message on the page after submitting the form via ajax.

I added in my form: remote => true parameter. However, it seems like I cannot send a message in my application. As a test, I created a new application for rails and created a message model and view, etc. Using a form using scaffolding.

I added a remote control: remote => true to the generated form. It transfers data to db. I read, I can just update the controller to enable js with format.js, in this case updating the posts_controller.rb function for

def new
  @post = Post.new

  respond_to do |format|
    format.html # new.html.erb
    format.js
  end
end

Several tutorials said that you can simply add new.js.erb or create.js.erb (not sure what it should be) in the views / posts folder, and this should be done, but nothing happens except for the data.

I also tried:

format.js { render :js => "alert('Hello Rails');" }   

as a test.

I use rails 3.1 and don’t understand what I should try next

+3
source share
1 answer

You are almost there. The submitted form is processed by the create action, not the new one. You have syntax for processing html or js - you just need this in your create and create.js.erb action containing the js you want to display.

Your PostsController must have a line by line function

def create
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html 
      format.js 
    else
      format.html { render :action => 'new' }
      format.js   { render 'fail_create.js.erb' }
    end
  end
end

Create a file called create.js.erb (in the submission directory for messages) containing

alert('Hello Rails');

, , . fail_create.js.erb javascript, (, ).

+7

All Articles